You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AJAX、PHP、JS将JSON存入myDB.txt失败,求技术协助

Fixing Your JSON-to-TXT File Write Issue

Hey there, let's get this sorted out—you're almost there! The core issue is a mix of unexecuted code, malformed AJAX requests, and default form behavior messing things up. Here's the breakdown and fixed code:

Key Problems in Your Current Code

  • You defined savePHPfunc inside jsonFunc but never called it—so the AJAX request was never sent.
  • Your AJAX URL was formatted wrong: it should be save.php?myJSON=... (missing the ? parameter prefix and parameter name).
  • The form's submit button was triggering a page refresh, interrupting any AJAX request that might have fired.
  • No error handling or feedback for whether the write succeeded, making debugging hard.
  • PHP was missing checks for the incoming parameter and didn't add line breaks, so entries would pile together.

Fixed Code

1. Updated JavaScript

function jsonFunc(event) {
  // Prevent form from refreshing the page
  event.preventDefault();

  // Get form values
  const nn = document.getElementById('videoName').value;
  const vv = document.getElementById('videoUrl').value;
  
  // Create and stringify JSON object
  const obj = { "name": nn, "url": vv };
  const myJSON = JSON.stringify(obj);
  console.log(myJSON);

  // Send to PHP (now actually called!)
  savePHPfunc(myJSON);
}

function savePHPfunc(jsonData) {
  const xhr = new XMLHttpRequest();
  // Fix URL format + encode JSON to handle special characters
  const url = `save.php?myJSON=${encodeURIComponent(jsonData)}`;
  
  xhr.open("GET", url, true);
  
  // Add feedback for success/error
  xhr.onload = function() {
    if (this.status >= 200 && this.status < 300) {
      console.log("Data saved successfully!");
      // Clear form after success
      document.getElementById('videoName').value = "";
      document.getElementById('videoUrl').value = "";
    } else {
      console.error("Failed to save data:", this.statusText);
    }
  };
  
  xhr.onerror = function() {
    console.error("Network error occurred");
  };
  
  xhr.send();
}

2. Updated PHP (save.php)

<?php
// Check if the parameter exists first to avoid errors
if(isset($_GET["myJSON"])) {
  $jsonData = $_GET["myJSON"];
  // Add a newline so each entry is on its own line
  $txt = $jsonData . "\n";
  
  // Open file in append mode
  $myfile = fopen("myDB.txt", "a") or die("Unable to open file!");
  fwrite($myfile, $txt);
  fclose($myfile);
  
  // Send success response back to JS
  echo "Data saved";
} else {
  // Send error response if no data was received
  http_response_code(400);
  echo "No data received";
}
?>

3. Updated HTML Form

<form>
  <input type="text" name="videoName" id="videoName" placeholder="Video name">
  <input type="text" name="videoUrl" id="videoUrl" placeholder="Video URL">
  <!-- Pass event to the function to prevent default submit -->
  <button type="submit" onclick="jsonFunc(event)">Add video</button>
</form>

Additional Checks

  • Make sure myDB.txt has write permissions on your server (usually set to 664 or 775 via FTP or chmod command).
  • If you're testing locally (e.g., with XAMPP/WAMP), ensure the file is in the same directory as your PHP and HTML files.

内容的提问来源于stack exchange,提问作者Ilhom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:23:42