简体   繁体   English

使用 vanilla AJAX(不是 JQuery)将 JSON 文档发送到 PHP 脚本

[英]Send JSON document to PHP script using vanilla AJAX (not JQuery)

I'm attempting to send a JSON document to a PHP script using AJAX.我正在尝试使用 AJAX 将 JSON 文档发送到 PHP 脚本。 The JSON document is constructed from the value of a <textarea> . JSON 文档由<textarea>的值构成。

I have successfully executed the solution using JQuery, and (for fun?.) am working on achieving the same result with vanilla AJAX.我已经使用 JQuery 成功执行了该解决方案,并且(为了好玩?。)正在努力使用香草 AJAX 实现相同的结果。

The calling PHP script:调用 PHP 脚本:

<script>
  function preview() {
    var xhttp;
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("output").innerHTML = this.responseText;
      }
    };
    var postData = {
        'html' : document.getElementById("editor").value,
    };
    xhttp.open("POST", "markuppreview.php");
    xhttp.setRequestHeader('Content-type', 'application/json');
    xhttp.send(postData);
  };
</script>

<pre><textarea id="editor" name="content" placeholder="Enter your markup"></textarea></pre><br />
<button value="Preview" onclick="preview();">Preview</button>
<h2>Preview</h2>
<div id="output" style="height:100px"></div>

The receiving PHP:接收 PHP:

$Parsedown = new Parsedown();
$Parsedown->setSafeMode(true);

$data['success'] = false;
$data['output'] = '';
if ($_POST['html']) {
    $data['success'] = true;
    $data['output'] = $Parsedown->text($_POST['html']);
}
echo json_encode($data);

I receive the following error, and can't work out why the postData.html isn't being received.我收到以下错误,无法弄清楚为什么没有收到 postData.html。

Warning: Undefined array key "html" in /Library/WebServer/Documents/markuppreview.php on line 8
{"success":false,"output":""}

I also tried a Javascript object method for constructing the JSON document, but received the same message.我还尝试了构建 JSON 文档的 Javascript object 方法,但收到了相同的消息。 When I alert the JSON document, it does show an html element with the data from the <textarea> .当我alert JSON 文档时,它确实显示了一个 html 元素,其中包含来自<textarea>的数据。

    var postData = new Object();
    postData.html = document.getElementById("editor").value;
    postData = JSON.stringify(postData);
    alert(postData);

Because you're attempting to send JSON-formatted data and $_POST works with form data, not a JSON payload.因为您正在尝试发送 JSON 格式的数据,并且$_POST使用表单数据,而不是 JSON 有效负载。

You'll need to do你需要做

$json = json_decode(file_get_contents('php://input'));

to read the POST input as a raw string, then JSON decode it.将 POST 输入读取为原始字符串,然后 JSON 对其进行解码。

Also, please use fetch() instead of the (pretty legacy) XMLHTTPRequest API.另外,请使用fetch()代替(相当旧的) XMLHTTPRequest API。

There are multiple problems coming together here:这里有多个问题:

  1. You seem to attempt to send JSON (according to your Content-Type: application/json header), yet PHP natively only supports form data.您似乎试图发送 JSON (根据您的Content-Type: application/json标头),但 PHP 本身仅支持表单数据。 If you want to use JSON, then you have to access the raw body with file_get_contents('php://input') and use json_decode on it to get an object (instead of using the associative array superglobal $_POST ).如果您想使用 JSON,那么您必须使用file_get_contents('php://input')访问原始正文并在其上使用json_decode以获取 object(而不是使用关联数组超全局$_POST )。

  2. You don't actually send anything useful, because you are passing an object to XMLHttpRequest#send which will get coerced to a string and end up as just [object Object] .您实际上并没有发送任何有用的东西,因为您将 object 传递给XMLHttpRequest#send ,这将被强制转换为字符串并最终成为[object Object] If you do want to send JSON, you'll have to apply JSON.stringify on the data first and send the result.如果您确实想发送 JSON,则必须先对数据应用JSON.stringify并发送结果。

Going from here, you can either change both client and server to fully use JSON or update the client to send form data.从这里开始,您可以更改客户端和服务器以完全使用 JSON 或更新客户端以发送表单数据。

However, I would recommend to switch to a more modern (and easy-to-use) solution than XMLHttpRequest anyway, ideally fetch .但是,无论如何,我建议切换到比XMLHttpRequest更现代(且易于使用)的解决方案,最好是fetch . With the existing server code (using form data), the following client code would work:使用现有的服务器代码(使用表单数据),以下客户端代码可以工作:

async function preview () {
  const response = await fetch('markuppreview.php', {
    method: 'POST',
    body: new URLSearchParams({ html: document.getElementById("editor").value })
  })
  document.getElementById('output').innerHTML = await response.text()
}

Final solution as per @CherryDT's suggestions.根据@CherryDT 的建议的最终解决方案。

Calling PHP script:调用 PHP 脚本:

<script>
async function preview () {
    const response = await fetch('markuppreview.php', {
          method: 'POST',
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
          body: new URLSearchParams({ html: document.getElementById("editor").value })
    })
    const { success, output } = await response.json()
    if (success) document.getElementById('output').innerHTML = output
}
</script>
<pre><textarea id="editor" name="content" placeholder="Enter your markup"></textarea></pre><br />
<button value="Preview" onclick="preview();">Preview</button>
<h2>Preview</h2>
<div id="output" style="height:100px"></div>

Receiving PHP:接收 PHP:

$Parsedown = new Parsedown();
$Parsedown->setSafeMode(true);

$data['success'] = false;
$data['output'] = '';
if ($_POST['html']) {
    $data['success'] = true;
    $data['output'] = $Parsedown->text($_POST['html']);
}
echo json_encode($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM