1

我正在尝试将 JSON 对象发送到 Web api,但遇到了一些麻烦。它应该从输入中获取值,首先检查响应,如果响应正确,则发送数据。这是我的 JS 代码:

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");
};

但是,在发送它时,我在控制台中收到 HTTP 500 错误,并且服务器本身的输出显示:

Processing request on /data
Caught error: <unspecified file>(1): expected object or array

这是 console.log 的结果:

{"data":{"val":"2"}}

我以为我正确地发送了数据,但它没有识别它。他们给出的示例是一个 .json 文件,并且工作正常,但我的字符串化 JSON 不起作用。

任何帮助将不胜感激

4

0 回答 0