我正在进行一个AJAX调用,在json响应中从服务器接收多个响应。我想获得每个响应的id
值。以下是服务器响应的示例:
{
"success": true,
"warnings": [],
"errors": [],
"requestId": "78098802gdu8",
"result": [{ * * * "id": 1536 * * * , "name": "test\n ", "description": null, "createdAt": "2015-09-23T18:44:46Z+0000", "updatedAt": "2015-09-23T18:44:46Z+0000", "url": "https://some.name.com/"
}]
我可以从单个回复中获得id
,但是我从多个回复中获取ids
并没有太大成功,例如:
{
"success": true,
"warnings": [],
"errors": [],
"requestId": "78098802gdu8",
"result": [
{ * * * "id": 1536 * * * , "name": "test\n ", "description": null, "createdAt": "2015-09-23T18:44:46Z+0000", "updatedAt": "2015-09-23T18:44:46Z+0000", "url": "https://some.name.com/"}]
{
"success": true,
"warnings": [],
"errors": [],
"requestId": "78098802gdu8",
"result": [{ * * * "id": 1537 * * * , "name": "test\n ", "description": null, "createdAt": "2015-09-23T18:44:46Z+0000", "updatedAt": "2015-09-23T18:44:46Z+0000", "url": "//some.name.com/"}]
{
"success": true,
"warnings": [],
"errors": [],
"requestId": "78098802gdu8",
"result": [{ * * * "id": 1538 * * * , "name": "test\n ", "description": null, "createdAt": "2015-09-23T18:44:46Z+0000", "updatedAt": "2015-09-23T18:44:46Z+0000", "url": "//some.name.com/"}]
}
}
}
另外,一旦我得到ids
,我想在div中显示它们。在此先感谢您的帮助!
以下是用于从一个响应中获取id的代码:
$.ajax({
type: "POST",
url: "somefile.php",
data: {
EmailName: Names,
Type: EmailType
},
success: function (results) {
var json = $.parseJSON(results);
$('textarea').val(JSON.stringify(json.result[0].id));
}
});
答案 0 :(得分:0)
重新构建您的问题。您希望将一种类型的数组(包含具有一种结构类型的对象(包含id))转换为另一种类型 - 仅包含ID的数组。
然后答案很清楚。 Javascript数组类型具有允许您执行此转换的映射操作。您只需要提供一个可以将包含id的结构转换为id的函数。
见这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
答案 1 :(得分:0)
以下单元测试显示了您的成功回调如何通过将ID附加到当前值来更新textarea
。
/* FUNCTION THAT MAKES AJAX REQUEST */
function doAsyncThing() {
$.ajax({
type: "POST",
url: "somefile.php",
// data: {…},
success: function (results) {
var json = $.parseJSON(results),
id = json.result[0].id,
val = $('textarea').val();
$('textarea').val(val + ' ' + id);
}
});
}
/* BEGIN UNIT TEST */
// CREATE CLOSURE TO RETURN DUMMY FUNCTION AND FAKE RESPONSE
function ajax_response(response) {
return function (params) {
params.success(response);
};
}
var n = prompt("Number of AJAX calls to make", 10);
for (var i = 1; i <= n; ++i) {
// OVERRIDE $.ajax WITH DUMMY FUNCTION AND FAKE RESPONSE
$.ajax = ajax_response('{ "result": [{ "id": ' + i + ' }] }');
doAsyncThing();
}
/* END UNIT TEST */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>IDs:</textarea>