如何将两个变量中的 json 响应分开?
现在 json 响应看起来
["AG","ANTIGUA AND BARBUDA","AU","AUSTRALIA","BR","BRAZIL","CA","CANADA"]
我可以使它
["AG,ANTIGUA AND BARBUDA","AU,AUSTRALIA","BR,BRAZIL","CA,CANADA"]
更容易使用或任何其他样式。
我需要的是将其分成两个变量,一个用于国家代码,另一个用于国家名称
...success: function( json ) {
$.each(json, function(i, value) {
$('#country').append($('<option>').text(value).attr('value', value));
};
});
,现在相同的变量进入选项的值和名称,我需要将国家代码放入选项中,将国家名称放入变量中。
Right now json response looks like
["AG","ANTIGUA AND BARBUDA","AU","AUSTRALIA","BR","BRAZIL","CA","CANADA"]
i can make it
["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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不首先将它们作为 JSON 对象返回?类似的事情
然后你可以做类似的事情
编辑:
上面的代码假设您已经将从服务器发送的数据转换为 JavaScript 数组。有两种方法可以解决此
getJSON
< /a> 方法,jQuery 将为您解析返回值自己解析数据parseJSON
这两种方法都会采用格式良好的 JSON 字符串,并返回一个可供使用的 JavaScript 对象
Why not return them as JSON objects in the first place? Something like
Then you could do something like
EDIT:
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:
getJSON
method and jQuery will parse the return value for youparseJSON
Either method will take a well formated JSON string and give you back a JavaScript object to work with
如果您选择第二个选项,您可以拆分字符串因此
编辑:您需要首先解析 JSON 字符串,以便可以使用数组对象并循环遍历它。请参阅上面我更新的代码。
If you go with your 2nd option you can split the string as such
EDIT: You need to parse the JSON string first, so you can use the Array Object and loop through it. See my updated code above.
如果你能做到:
那么你可以使用这个:
If you can make it:
Then you could use this:
如果您想采用以下方法:
并使其成为键/值对对象的数组,您可以执行以下操作:
您最终会在
result
中得到与此等效的结果:更新:如果全部您关心的是将这些添加到选择中,您可以这样做:
对于它的价值,在这种情况下可能可以忽略不计,但这种方法相对较慢。如果您发现性能问题,请考虑在添加选项时使用
.detach()
方法将#country
从 DOM 中拉出,然后将其附加回结尾。If you want to take this:
And make it an array of key/value pair objects, you could do something like this:
You'll end up with the equivalent of this in
result
:Update: If all you care about is adding those to the select, you can do it this way:
For what it's worth, it may be negligible in this case, but this approach is relatively slow. If you notice performance issues, look into using the
.detach()
method to pull#country
out of the DOM while the options are being added and then attaching it back at the end.