简体   繁体   English

使用jQuery从JSON访问数据

[英]accessing data from JSON using jQuery

Need help on code to provide iteration of this JSON response: 需要有关代码的帮助以提供此JSON响应的迭代:

JSON Response: JSON响应:

[{"id":"1","FK_country":"USA","FK_state":"Arizona","FK_city":"Phoenix","zip":"85001","update_by":"SYSTEM","update_when":"0000-00-00 00:00:00"},
{"id":"2","FK_country":"USA","FK_state":"Arizona","FK_city":"Phoenix","zip":"85002","update_by":"SYSTEM","update_when":"0000-00-00 00:00:00"},
{"id":"3","FK_country":"USA","FK_state":"Arizona","FK_city":"Phoenix","zip":"85003","update_by":"SYSTEM","update_when":"0000-00-00 00:00:00"}]

The code I have UPDATED with assistance from suggestions below is 我在以下建议的帮助下已更新的代码是

function test3 () 
{

    var myCriteria = "";

    var key = "mykey";

    myCriteria = $( "#city" ).val();

    $('#myTestDiv').empty().append(myCriteria);

    var myDataRequest = $.ajax({
                url: 'ajx_zip.php',
                type: 'POST',
                dataType: 'json',
                data: {city:myCriteria, api_key:key},
                success: function(myData)
                {
                    alert( "Data Request Success!" );

                    $('#zip')
                    .find('option')
                    .remove()
                    .end();

                    $( "#myTestDiv" ).append( "<p>" + myData + "</p>" );

                    var myNewData = $.parseJSON(myData);

                    $( "#myTestDiv" ).append( "<p>" + myNewData + "</p>" );

                    $.each(myNewData, function(i, value) 
                    {
                    $('#zip').append($('<option></option>').val(value.FK_city).html(value.FK_city));
                    });
                }

        });

    myDataRequest.fail(function(jqXHR, textStatus)
    {
    if (jqXHR.status === 0)
    {
        alert('Not connect.n Verify Network.');
    }
    else if (jqXHR.status == 404)
    {
        alert('Requested page not found. [404]');
    }
    else if (jqXHR.status == 500)
    {
        alert('Internal Server Error [500].');
    }
    else if (exception === 'parsererror')
    {
        alert('Requested JSON parse failed.');
    }
    else if (exception === 'timeout')
    {
        alert('Time out error.');
    }
    else if (exception === 'abort')
    {
        alert('Ajax request aborted.');
    }
    else
    {
        alert('Uncaught Error.n' + jqXHR.responseText);
    }
    });

 }

The HTML code I have UPDATED from suggestions for this is: 我从建议中得到更新的HTML代码是:

<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<script language="javascript" src="select.js"></script>
</head>

<body>

<h3>Test Address for Javascript</h3>

<FORM name="address" action="testresult.php" method="POST" >

<SELECT  ID="country" NAME="country" >
<Option value="">Select Country</option>
<Option value="USA">United States</option>
<Option value="CAN">Canada</option>
</SELECT>

<br><br>

<SELECT id="state" NAME="state">
<Option value="Arizona">Arizona</option>
<Option value="California">California</option>
</SELECT>

<br><br>

<SELECT id="city" NAME="city" onchange="test3();">
<Option value="Phoenix">Phoenix</option>
<Option value="Glendale">Glendale</option>
<Option value="Chandler">Chandler</option>
<Option value="California">California</option>
</SELECT>

<br><br>

<SELECT id="zip" NAME="zip">
<Option value="Select Zip">Select Zip</option>
</SELECT>

</form>

<div id="myTestDiv"></div>
</body>

</html>

In addition, I have created a simple html-form POST test from same server to PHP processing page and I produce now a limited data-set speeding client-side performance created to test the API - all works well in producing expected results as demonstrated at the top of this post (an echo of the 'results' page). 此外,我已经创建了一个从同一台服务器到PHP处理页面的简单html形式的POST测试,现在我生成了一个有限的数据集,以加快为测试API而创建的客户端性能-所有这些都很好地产生了预期的结果,如下所示这篇文章的顶部(“结果”页面的回声)。 However the error now occurs with processing of the JSON object within the Javascript function at the $.parseJSON level. 但是,错误现在在$ .parseJSON级别在Javascript函数中处理JSON对象时发生。 In the test output DIV my appended output is as follows... 在测试输出DIV中,我附加的输出如下...

Chandler
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Replace this: 替换为:

<SELECT id="city" NAME="city" onselect="AddZipOptions();">

with this: 有了这个:

<SELECT id="city" NAME="city" onchange="AddZipOptions();">

onSelect is an event fired when you select some text with the mouse! onSelect是当您用鼠标选择一些文本时onSelect的事件!

You should also clean the zip select before appending the results: 您还应该在添加结果之前清理zip select:

$("#zip").children(':not(:first)').remove()
$("#zip").append($('<option>', {text: result.zip, value: result.zip}));

Try adding this to the ajax parameters 尝试将其添加到ajax参数

$.ajax({
                  datatype: "json",
    });

and try calling this in your success function before the each. 并尝试在每个成功函数中调用此函数。

       var newMyData = $.parseJSON(myData);

and then use the new variable. 然后使用新变量。

The answer to this question was solved by both @lazel and @dancer and a previous post found here... Ajax success function returning [object, object] ...the JSON response was already parsed as one commentator suggested, but the data returned had already processed as objects within an object. @lazel和@dancer都解决了这个问题的答案,并且在这里找到了以前的文章... Ajax成功函数返回[object,object] ...已经将JSON响应解析为一个注释者的建议,但是返回了数据已经作为对象在对象中处理。

Solved and working with this updated code. 解决并使用此更新的代码。

Hopefully this will help other JQuery newbies. 希望这对其他JQuery新手有所帮助。 Thank you contributors! 谢谢贡献者!

function slct_zip () 
    {

        var myCriteria = "";

        var key = "yourAPIkeyhere";

        myCriteria = $( "#city" ).val();

        var myDataRequest = $.ajax({
                    url: 'yourphpqueryscriptinJSON.php',
                    type: 'POST',
                    dataType: 'json',
                    data: {city:myCriteria, api_key:key},
                    success: function(myData)
                    {
                        alert( "Please Select Zip" );

                        $('#zip')
                        .find('option')
                        .remove()
                        .end();

                        for (var i=0;i<myData.length;i++) 
                            {
                            $( "#zip" ).append($('<option></option>').val(myData[i].zip).html(myData[i].zip));
                            }
                    }

            });

        myDataRequest.fail(function(jqXHR, textStatus)
        {
        if (jqXHR.status === 0)
        {
            alert('Not connect.n Verify Network.');
        }
        else if (jqXHR.status == 404)
        {
            alert('Requested page not found. [404]');
        }
        else if (jqXHR.status == 500)
        {
            alert('Internal Server Error [500].');
        }
        else if (exception === 'parsererror')
        {
            alert('Requested JSON parse failed.');
        }
        else if (exception === 'timeout')
        {
            alert('Time out error.');
        }
        else if (exception === 'abort')
        {
            alert('Ajax request aborted.');
        }
        else
        {
            alert('Uncaught Error.n' + jqXHR.responseText);
        }
        });

     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM