gpt4 book ai didi

javascript - 将 json 从 Javascript 发送到 Javascript

转载 作者:行者123 更新时间:2023-11-30 16:21:27 26 4
gpt4 key购买 nike

我在 jsp 中有一个 js,我想在另一个 js 中发送一个 json。

在jsp中console.log(html_out);正确打印 json。

  $.ajax({
//ajax code
},
async: true
})
.done(function(html_out) {
console.log(html_out);
drawTable(html_out);

})

console.log(html_out) 的输出:

{ title: "hello1", name: "nam1" },{ title: "hello2", name: "nam2" }

但是,在 js 中,json 不会将数据放在我想要放置的表中。 console.log(rowData);显示:

 { 
t
i
t
l
e
:
"
h
...
...

这是我要打印 json 的 js 代码:

function drawTable(data){

for (var i=0; i<data.length; i++){
drawRow(data[i]);
}
}
function drawRow(rowData) {
console.log(rowData);
var row = $("<tr />")
$("#farmacyDataTable").append(row);
row.append($("<td>" + rowData.title + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));

}

最佳答案

如 dfsq 所述,您必须将 JSON 字符串解析为 JavaScript 对象,现在您正在迭代该字符串

$.ajax({
//... ajax code
async: true, // Not needed, it default to async: true, async:false is deprecated
// If you add the line below, you don't need to parse the response
// dataType: 'json'
})
.done(function(html_out)
drawTable(JSON.parse(html_out));
})

如果您为响应正确设置了 MIME 类型(在服务器上),则无需调用 JSON.stringify

http://api.jquery.com/jquery.ajax/

dataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

关于javascript - 将 json 从 Javascript 发送到 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34677510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com