duanbipu1720 2017-01-08 00:29
浏览 67
已采纳

被JQuery $ .each行为困扰

I have a php file which when called returns a simple non associative array of string values. When I request the array using the jQuery get routine I get the array I expect, but when I try to iterate it , instead of getting the two string values, the $.each command iterates every char. I don't understand what I'm getting wrong.

My code:

<div name ="test_spot" id ="test_spot" width="200" height="400">Test</div> 

<script type="text/javascript">

function getOutput(){

    $.get( "data.php", function( data ) {

        // This call verifies the the array is what I would expect.
        // ["one","two"]. Then I comment this out and run the code below.
        //$( "#test_spot" ).html( data);

        $.each(data,  function(index, value){

            // This outputs each char instead of each string each on its own line in the div.
            // [
            // "
            // o
            // n
            // e etc
            $('#test_spot').append($('<p>').text(value)); 

        });

    });
}

</script>

<button onClick="getOutput()" style="height: 60px; width:100px;" >Test</button>

Thanks for the help.

  • 写回答

1条回答 默认 最新

  • doujiao7325 2017-01-08 00:49
    关注

    You are expecting an object but are getting back a JSON string. When you pass that to .each it iterates over the characters in the string.

    Try specifying the dataType as json like this:

    $.get( "data.php", function( data ) { 
            $.each(data,  function(index, value){ 
                 $('#test_spot').append($('<p>').text(value)); 
            });
    
    }, "json" );
    

    Or, like charlietfl points out, simply use

    $.getJSON( "data. php", function( data ) {
            $.each(data,  function(index, value){ 
                 $('#test_spot').append($('<p>').text(value)); 
            });
    });
    

    If that still doesnt work, Id look at the output and make sure that it is valid JSON.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比