jQuery技术:循环收到的json字符串以通过jquery获取值

我正在尝试解析从$.post()返回的数据。

 [{"id":"1","text":"USD"}, {"id":"2","text":"CNY"}, {"id":"3","text":"PHP"}, {"id":"4","text":"AUD"}, {"id":"5","text":"SGD"}, {"id":"6","text":"JPY"}] 

使用这种方法Jquery,循环遍历json数组

我做了这样的事情:

 $.post( base_url+'cgame/currency', { gameID: gameID }, function(data) { $(this).html(); $.each(data,function(idx, obj) { $(obj).each(function(key, value) { console.log(key + ": " + value); }); }); } ); 

但它给了我错误:

未捕获的TypeError:无法使用’in’运算符在[{"id":"2","text":"CNY"},{"id":"3","text":"PHP"},{"id":"4","text":"AUD"},{"id":"5","text":"SGD"},{"id":"6","text":"JPY"}] ”中搜索“120” [{"id":"2","text":"CNY"},{"id":"3","text":"PHP"},{"id":"4","text":"AUD"},{"id":"5","text":"SGD"},{"id":"6","text":"JPY"}]

我也尝试过:

 $.post( base_url+'cgame/currency', { gameID: gameID }, function(data) { $(this).html(); $(data).each(function(idx, obj) { $(obj).each(function(key, value) { console.log(key + ": " + value); }); }); } ); 

但它也给了我错误:

未捕获错误:语法错误,无法识别的表达式: [{"id":"1","text":"USD"},{"id":"6","text":"JPY"}]

我该怎么做?

    您的数据以数组的forms出现,因此您需要循环遍历每个索引,然后获取值。 所以你可以替换这个: –

      $(obj).each(function(key, value) { console.log(key + ": " + value); }); 

    与: –

      $.each( obj, function( key) { console.log( obj[key].id + ':' + obj[key].text); }); 

    或者你可以这样做: –

      $.each( obj, function( key, value ) { console.log( value.id + ':' + value.text); }); 

    key是数组的索引。 它将返回0,1,2 ..

    我认为传递给你的成功回调函数的参数是string类型。 将其更改为:

      function(data) { var parsedData = JSON.parse(data); $(this).html(); $.each(parsedData ,function(idx, obj) { $(obj).each(function(key, value) { console.log(key + ": " + value); }); }); } 

      function(data) { var value = JSON.parse(data); $.each(value ,function(idx, obj) { console.log("id : "+obj.id+" "+text:"+obj.text); }); } 

    试试这个

     $.post(base_url+'cgame/currency',{ gameID: gameID }, function(data) { $(this).html(); //<-- becareful $(this) might not be the element you think it is $.each(data,function(idx, obj) { console.log( "id : " + obj.id); console.log( "text: " + obj.text); }); },'JSON'); 

      以上就是jQuery教程分享循环收到的json字符串以通过jquery获取值相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/jquerytutorial/541525.html

      (0)
      上一篇 2021年1月4日
      下一篇 2021年1月4日

      精彩推荐