如何在两个变量中分离json响应? [英] How to separate json response in two variables?
问题描述
现在json响应看起来像
Right now json response looks like
["AG","ANTIGUA AND BARBUDA","AU","AUSTRALIA","BR","BRAZIL","CA","CANADA"]
我可以做到
["AG,ANTIGUA AND BARBUDA","AU,AUSTRALIA","BR,BRAZIL","CA,CANADA"]
如果更易于使用或使用其他样式.
if thas easier to work with or any other style.
我需要将其分为两个变量,一个用于县区代码,另一个用于国名
what i need is to separate it into two variables one for county code other for country name
...success: function( json ) {
$.each(json, function(i, value) {
$('#country').append($('<option>').text(value).attr('value', value));
};
});
现在,相同的变量的值和选项名称中都包含了变量,我需要在选项中输入国家代码,在变量中输入国家名称.
now same variable goes in value and name of option i need to put country code in option and country name in variable.
推荐答案
为什么不首先将它们作为JSON对象返回?像
Why not return them as JSON objects in the first place? Something like
[{"ID":"AG", "Text":"ANTIGUA AND BARBUDA"},{"ID":"AU", "Text":"Australia"}]
然后您可以做类似的事情
Then you could do something like
$.each( result, function( value ){
$('#country').append(
$("<option>").text(value.Text).attr("value", value.Text)
);
});
上面的代码假定您已经将从服务器发送的数据转换为JavaScript数组.有两种方法可以解决此问题:
The above code assumes you've already converted the data sent from the server into a JavaScript array. There are two ways to approach that:
- You can request the data using the
getJSON
method and jQuery will parse the return value for you - You can parse the data yourself using the
parseJSON
这两种方法都将采用格式正确的JSON字符串,并带给您可以使用的JavaScript对象
Either method will take a well formated JSON string and give you back a JavaScript object to work with
这篇关于如何在两个变量中分离json响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!