Javascript 服务器API不接受JSON发送
我试图向web api发送一个JSON对象,但遇到了一点麻烦。它应该从输入中获取值,首先检查响应,如果响应正确,则发送数据。以下是我的JS代码:Javascript 服务器API不接受JSON发送,javascript,json,object,Javascript,Json,Object,我试图向web api发送一个JSON对象,但遇到了一点麻烦。它应该从输入中获取值,首先检查响应,如果响应正确,则发送数据。以下是我的JS代码: var form = document.getElementById("inputForm"), master = {}, xhr = new XMLHttpRequest(); //global variables used for checking different parts of the process form.onsubmit = fun
var form = document.getElementById("inputForm"), master = {}, xhr = new XMLHttpRequest(); //global variables used for checking different parts of the process
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
master.data = data;
}
// construct an HTTP request
function get(url, callback) {
xhr.open("GET", url);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var type = xhr.getResponseHeader("Content-Type");
if (type.indexOf("xml") !== -1 && xhr.responseXML)
callback(xhr.responseXML);
else if (type === "application/json")
callback(JSON.parse(xhr.responseText));
else
callback(xhr.responseText);
}
};
// send the collected data as JSON
console.log(JSON.stringify(master));
xhr.send(JSON.stringify(master));
}
get("http://example.com:12321/data");
};
我以为我发送的数据是正确的,但它无法识别。他们给出的示例是一个.json文件,该文件运行良好,但我的字符串化json不起作用
任何帮助都将不胜感激您必须在服务器上运行json解码,才能从编码字符串创建数组/对象。通过php,json_decode函数可以做到这一点。@inf3rno是否有办法通过XMLHttpRequest发送该信息?否。您在客户端对数据进行编码,将其作为json序列化字符串发送到服务器,然后在服务器上对其进行解码。。。500错误意味着内部服务器错误,因此问题在于服务器端代码,而不是客户端。。。检查服务器上的错误日志!顺便说一句,如果使用XHR发送数据,POST方法会更好。GET用于显示数据。。。
Processing request on /data
Caught error: <unspecified file>(1): expected object or array
{"data":{"val":"2"}}