Javascript 从AJAX返回JSON对象获取某些值
我试图在从AJAX检索的JSON对象中检索某些值 使用Javascript 从AJAX返回JSON对象获取某些值,javascript,jquery,html,json,ajax,Javascript,Jquery,Html,Json,Ajax,我试图在从AJAX检索的JSON对象中检索某些值 使用console.log(),我可以查看以下内容: 0: Object title: "First post" body: "This is a post" id: 1 userId: 27 . . . 100: //same format of data as object 0 现在我想尝试存储上面的整个JSON对象,这样我就可以使用userId,并将其与另一个数据列表匹配,以找到发表文章的用户。问题是,我无法将其存
console.log()
,我可以查看以下内容:
0: Object
title: "First post"
body: "This is a post"
id: 1
userId: 27
.
.
.
100: //same format of data as object 0
现在我想尝试存储上面的整个JSON对象,这样我就可以使用userId
,并将其与另一个数据列表匹配,以找到发表文章的用户。问题是,我无法将其存储到全局变量。以下是我的jscript代码片段:
var postJson; //global variable
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
console.log(response);
}
});
我也尝试过做
postJson=$。ajax
但没有发生任何事情,postJson
仍然没有定义。$。ajax是异步函数,您需要使用回调函数或在success函数中执行所有代码
var postJson; //global variable
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
//do something with postJson or call function doSomething(response)
}
});
您可以直接从响应中调用函数,无需声明变量。希望它也能帮助您在收到ajax响应之前,您可能正在尝试使用
postJson
变量。我认为,如果您在success
处理程序中对其进行控制台处理,您将打印预期的json对象。当您尝试将其存储到全局变量时,错误消息是什么?可能没有错误消息的重复。但是,当我在success之外使用console.log(postJson)时,它在控制台中显示为“未定义”。
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
doSomething(response);
//do something with postJson or call function doSomething(response)
}
});