从PHP传递JSON阿贾克斯() [英] Pass JSON from PHP to ajax()

查看:136
本文介绍了从PHP传递JSON阿贾克斯()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的ajax():

 <脚本>
        $(文件)。就绪(函数(){
            $(形式)。递交(函数(){
                VAR URL =xxx.php /;
                VAR参数= $(#streetInput)序列化()+&放大器;。
                    参数+ = $(#cityInput)序列化()+&放大器;。
                    参数+ = $(#stateInput)序列化()。

                    $阿贾克斯({
                            网址:网址,
                            数据:参数,
                            键入:GET,
                            数据类型:JSON,
                            成功:功能(数据){
                                //这里分析数据
                                警报(数据);
                            },
                            错误:函数(){
                                警报(错误);
                            }
                        });
            });

        });
< / SCRIPT>
 

和我成功地传递参数给xxx.php文件,也将一些数据,以JSON形式和正确回应他们。

 < PHP
$ streetArr =阵列(); $ cityArr =阵列();
$街头= $城市= $状态=;
$ URL ='http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=myid&';


如果($ _ SERVER [REQUEST_METHOD] ==GET)
{

    $街头= test_input($ _ GET [streetInput]);
    $城市= test_input($ _ GET [cityInput]);
    $状态= test_input($ _ GET [stateInput]);
    $ streetArr = strsToArray($街道);
    $ cityArr = strsToArray($的城市);

    $ URL = $网址。 地址=。 $ streetArr [0];
    为($ X = 1; $ X<计数($ streetArr); $ X ++)
        如果($ streetArr [$ X]!=#)
            $ URL =+ $ streetArr [$ X]。

    $ URL = $网址。与& citystatezip =。 $ cityArr [0];
    为($ X = 1; $ X<计数($ cityArr); $ X ++)
        $ URL =+ $ cityArr [$ X]。

    $ URL = $网址。 %2C +。 $状态。 &放大器; rentzestimate =真;

    $ XML =使用simplexml_load_file($网址);
    回声json_en code($ XML);

    ..... //某些功能
}
 

但是当我调试在Firefox使用Firebug,我不能让警报(数据),但警报(错误)代替。我不知道为什么我的ajax()请求没有成功。

我得到了服务器端的JSON数据:

  {请求:{地址:2636万络街,citystatezip:洛杉矶,加州},消息:{文:请求成功processed","$c$c":"0"},"response":{"results":{"result":{"zpid":"20593083","links":{"homedetails":"http:\/\/www.zillow.com\/homedetails\/2636-Menlo-Ave-Los-Angeles-CA-90007\/20593083_zpid\/","graphsanddata":"http:\/\/www.zillow.com\/homedetails\/2636-Menlo-Ave-Los-Angeles-CA-90007\/20593083_zpid\/#charts-and-data","mapthishome":"http:\/\/www.zillow.com\/homes\/20593083_zpid\/","comparables":"http:\/\/www.zillow.com\/homes\/comps\/20593083_zpid\/"},"address":{"street":"2636门罗大道,拉链code:90007,城市:洛Angeles","state":"CA","latitude":"34.03163","longitude":"-118.289972"},"FIPScounty":"6037","use$c$c":"Duplex","taxAssessmentYear":"2013","taxAssessment":"152082.0","yearBuilt":"1924","lotSizeSqFt":"5242","finishedSqFt":"1728","bathrooms":"2.0","bedrooms":"2","lastSoldDate":"07\/29\/1996","lastSoldPrice":"115000","zestimate":{"amount":"452915","last-updated":"10\/26\/2014","oneWeekChange":{"@attributes":{"de$p$pcated":"true"}},"valueChange":"3507","valuationRange":{"low":"375919","high":"520852"},"percentile":"0"},"rentzestimate":{"amount":"1887","last-updated":"10\/27\/2014","oneWeekChange":{"@attributes":{"de$p$pcated":"true"}},"valueChange":"-9","valuationRange":{"low":"1415","high":"2680"}},"localRealEstate":{"region":{"@attributes":{"id":"268581","type":"neighborhood","name":"West Adams"},"links":{"overview":"http:\/\/www.zillow.com\/local-info\/CA-Los-Angeles\/West-Adams\/r_268581\/","forSaleByOwner":"http:\/\/www.zillow.com\/west-adams-los-angeles-ca\/fsbo\/","forSale":"http:\/\/www.zillow.com\/west-adams-los-angeles-ca\/"}}}}}}}
 

在我点击提交按钮,然后它显示警报(错误),然后再重定向到xxx.php为我指定

解决方案
  

数据类型:JSON,

会特意去找的内容类型是JSON和你只能解析响应时,数据类型是真正的JSON。

像xrissz指出的那样,你需要用你设置的内容类型。

 标题(内容类型:应用程序/ JSON);
 

和它应该放在你面前回声/给出任何输出从您的脚本,通常在你的脚本的顶部。

This is my ajax():

<script>
        $(document).ready(function(){
            $("form").submit(function(){
                var url = "xxx.php/";
                var param = $("#streetInput").serialize() + "&";
                    param += $("#cityInput").serialize() + "&";
                    param += $("#stateInput").serialize();

                    $.ajax({
                            url: url,
                            data: param,
                            type: 'GET',
                            dataType: 'json',
                            success: function(data) {
                                // parse the data here
                                alert(data);
                            },
                            error: function(){
                                alert("error");
                            }
                        });
            });

        });
</script>

And I successfully pass parameters to xxx.php file, and also convert some data to JSON form and echo them correctly.

<?php
$streetArr = array(); $cityArr = array();
$street = $city = $state = "";
$url = 'http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=myid&';


if($_SERVER["REQUEST_METHOD"] == "GET")
{

    $street = test_input($_GET["streetInput"]);
    $city = test_input($_GET["cityInput"]);
    $state = test_input($_GET["stateInput"]);
    $streetArr = strsToArray($street);
    $cityArr = strsToArray($city);

    $url = $url . "address=" . $streetArr[0];
    for($x = 1; $x < count($streetArr); $x++)
        if($streetArr[$x] != "#")
            $url .= "+$streetArr[$x]";

    $url = $url . "&citystatezip=" . $cityArr[0];
    for($x = 1; $x < count($cityArr); $x++)
        $url .= "+$cityArr[$x]";

    $url = $url . "%2C+" . $state . "&rentzestimate=true";

    $xml = simplexml_load_file($url);
    echo json_encode($xml);

    ..... // some functions
}

but when I debug on Firefox with Firebug, I cannot get "alert(data)" but "alert("error")" instead. I don't know why my ajax() request not success.

I get the JSON data in server-side:

{"request":{"address":"2636 Menlo Street","citystatezip":"Los Angeles, CA"},"message":{"text":"Request successfully processed","code":"0"},"response":{"results":{"result":{"zpid":"20593083","links":{"homedetails":"http:\/\/www.zillow.com\/homedetails\/2636-Menlo-Ave-Los-Angeles-CA-90007\/20593083_zpid\/","graphsanddata":"http:\/\/www.zillow.com\/homedetails\/2636-Menlo-Ave-Los-Angeles-CA-90007\/20593083_zpid\/#charts-and-data","mapthishome":"http:\/\/www.zillow.com\/homes\/20593083_zpid\/","comparables":"http:\/\/www.zillow.com\/homes\/comps\/20593083_zpid\/"},"address":{"street":"2636 Menlo Ave","zipcode":"90007","city":"Los Angeles","state":"CA","latitude":"34.03163","longitude":"-118.289972"},"FIPScounty":"6037","useCode":"Duplex","taxAssessmentYear":"2013","taxAssessment":"152082.0","yearBuilt":"1924","lotSizeSqFt":"5242","finishedSqFt":"1728","bathrooms":"2.0","bedrooms":"2","lastSoldDate":"07\/29\/1996","lastSoldPrice":"115000","zestimate":{"amount":"452915","last-updated":"10\/26\/2014","oneWeekChange":{"@attributes":{"deprecated":"true"}},"valueChange":"3507","valuationRange":{"low":"375919","high":"520852"},"percentile":"0"},"rentzestimate":{"amount":"1887","last-updated":"10\/27\/2014","oneWeekChange":{"@attributes":{"deprecated":"true"}},"valueChange":"-9","valuationRange":{"low":"1415","high":"2680"}},"localRealEstate":{"region":{"@attributes":{"id":"268581","type":"neighborhood","name":"West Adams"},"links":{"overview":"http:\/\/www.zillow.com\/local-info\/CA-Los-Angeles\/West-Adams\/r_268581\/","forSaleByOwner":"http:\/\/www.zillow.com\/west-adams-los-angeles-ca\/fsbo\/","forSale":"http:\/\/www.zillow.com\/west-adams-los-angeles-ca\/"}}}}}}}

After I click submit button, then it shows alert("error") first and then redirect to xxx.php as I specified in

解决方案

dataType: 'json',

Will specifically look for content type to be json and you can only parse the response when the data type is real json.

Like xrissz pointed out, you will need to set your content type with

header('Content-type: application/json');

and it should be placed before you echo/give any output from your script, usually at the top of your script.

这篇关于从PHP传递JSON阿贾克斯()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆