如何使用javascript访问数组的JSON编码数据 [英] How to access JSON encoded data of an array using javascript
问题描述
如何使用javascript从服务器访问此响应。
这是json编码数据。
How can i access this response from server using javascript. This is the json encoded data.
[{"cid":"1234","city":"value1","district":"value2","state":"value3"}]
谢谢提前。
这是ajax代码:
function cityauto(ctid){
var city = document.getElementById(ctid);
if(city.value.length > 3){
$.ajax({
type: "GET",
url: "city.php",
data: {term: city.value},
success: function (data){
alert(data);
}
});
}
Html代码:
<input type="text" name="city" id="cty" onblur="cityauto(this.id);" />
onblur我在警告框中获得了来自php文件的响应现在我需要在javscript中访问这些值。
onblur i am getting above response from php file in alert box now i need to access that values in javscript.
推荐答案
假设JSON以字符串形式返回:
Assuming the JSON is returned as a string:
var data = '[{"cid":"1234","city":"value1","district":"value2","state":"value3"}]';
// Parse the data as json
var obj = JSON.parse(data)
// Access the ojbect:
console.log(obj);
console.log(obj[0]); // == Object {cid: "1234", city: "value1", district: "value2", state: "value3"}
console.log(obj[0].cid); // == 1234
[0]
是访问JSON中的第一个对象,这是一个数组。然后你只需添加 .name
,其中'name'是你想要的变量的名称。 (例如 .cid
)。
The [0]
is to access the first object inside the JSON, which is an array. Then you just add .name
, where 'name' is the name of the variable you want. (like .cid
).
如果JSON已经是对象,则可以跳过 JSON.parse()
:
If the JSON is already a object, you can skip the JSON.parse()
:
var obj = [{"cid":"1234","city":"value1","district":"value2","state":"value3"}];
并像上面的示例一样访问它。
(在这种情况下,这个问题更多是关于访问JavaScript对象而不是JSON)
And access it like the example above.
(In that case, this question is more about accessing JavaScript objects, instead of JSON)
在您的情况下,您可以访问如下数据:
In your case, you can access the data like this:
success: function (data){
var obj = JSON.parse(data);
// Do stuff with `obj` here.
}
这篇关于如何使用javascript访问数组的JSON编码数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!