我在通过 ajax 将帖子内容发送到 php 文件时遇到问题。我的目的是发送一个包含将在文件 save.php 中使用的数据的对象,并且它必须处理响应以便它出现在警报窗口中。
var iden = true;
var object = {
'titulo': 'In the mountain',
'dest': 'Single of',
'edit': true,
'previ': 'yes',
'iden': iden
};
var xhr = new XMLHttpRequest();
xhr.open('POST', "save.php", false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send( object);
if (xhr.status == 200) {
xhr.onload = function () {
alert(this.responseText);
};
} else {
alert('error');
}
问题是,当尝试发送数据时,我在控制台中收到此消息:
Test.js: 56 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
第 56 行对应于:
Xhr.open('POST','save.php', false);
如果我将 async 参数设置为 true,它会从条件 if (xhr.status == 200) 跳转到 else 并显示错误警报。
问题可能出在哪里?
另外说,使用 jquery 它可以完美地工作,但我想使用 Javascript 来完成。
使用 jquery:
$.ajax({
url: "save.php",
type: "post",
data: object
}).done(function(data) {
alert(data);
});
编辑:
console.log(xhr);
XMLHttpRequest {readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: function…} onabort : null onerror : null onload : null onloadend : null onloadstart : null onprogress : null onreadystatechange : function () ontimeout : null readyState : 4 response : "" responseText : "" responseType : "" responseURL : "http://localhost/save.php" responseXML : null status : 200 statusText : "OK" timeout : 0
最佳答案
尝试更改这行代码:xhttp.open("POST", "save.php", false);
并将第三个参数设置为true
。如果可行,请按照此示例进行操作。
var object = {
'titulo': 'In the mountain',
'dest': 'Single of',
'edit': true,
'previ': 'yes',
'iden': iden
};
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "save.php", true);
xhttp.send(object);
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
关于javascript - 我无法使用 javascript 通过 ajax 将内容发布到 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44360203/