在普通 js ajax 请求中发送数据

问题描述 投票:0回答:1

我无法理解在 httpc.send 中发送数据时的问题,我尝试了 JSON.stringify 但无能为力,返回始终为 null。有关ajax的不同主题没有问题。

var data = {
    concat_operation: params
};
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "calcul.php";


httpc.onreadystatechange = function() { //Call a function when the state changes.
    if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
        console.log(httpc.response); // some processing here, or whatever you want to do with the response
        // console.log(JSON.parse(httpc.responseText)); // some processing here, or whatever you want to do with the response
        var serverResponse = JSON.parse(httpc.responseText);
        console.log(serverResponse);
    }
};
httpc.open("POST", url, true); // sending as POST
console.log(data);
httpc.send(data);

但是,我设法在 Jquery 中做到了。一个我没想到的处理一定是Jquery支持的?

var data = {
    concat_operation: concat_number
};
$.post("calcul.php", data , function(response){
    var result = response.result;
    $('.parent').before(`<div class="result">${result}</div>`);
}, "json")
javascript jquery
1个回答
0
投票

您必须正确设置标头并发送字符串化数据

 httpc.open("POST", url, true); // sending as POST
 httpc.setRequestHeader("Content-type", "application/json");
 httpc.send(JSON.stringify(data));
© www.soinside.com 2019 - 2024. All rights reserved.