简体   繁体   English

使用jQuery在PHP中获取JSON响应

[英]Get JSON response in PHP using jQuery

Here is my code to call AJAX and get the response from another PHP file: 这是我的代码来调用AJAX并从另一个PHP文件获取响应:

$.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km},
        function(data){
            $('#fare').html(data);
            $('#loading_spinner').hide();

        });

ajaxscript.php file ajaxscript.php文件

$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';

$json = json_decode($jsonData,true);
echo $json['fare'];

This code gives me the fare at the time of $('#fare').html(data); 此代码给我在当时的票价 $('#fare').html(data);

But I need to extract the city from JSON, too, and for this I added an extra line in ajaxscript.php: 但是我也需要从JSON提取城市,为此,我在ajaxscript.php中添加了额外的一行:

echo $json['city'];

After doing this, it gives me 30580Islamabad 完成此操作后,它给了我30580Islamabad

How can I store these two values separately in JavaScript? 如何在JavaScript中分别存储这两个值? I need them for future work. 我需要它们以备将来之用。

You are doing everything backwards 你正在倒退

Your PHP should be 您的PHP应该是

$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';

//$json = json_decode($jsonData,true);
echo $jsonData;

As you already have a JSONString to send to your javascript. 由于您已经有一个JSONString发送到您的JavaScript。

Then your javascript will recieve a javascript object in the data parameter of 然后,您的javascript将在的data参数中接收一个javascript对象

$.post( '<?php echo get_site_url(); ?>/ajax-script/', 
          {pickup:pickup,dropoff:dropoff,km:km}, 
   function( data ) {
        $('#fare').html(data.fare);
        $('#city').html(data.city);
        $('#loading_spinner').hide();
}, "json");

Note the "JSON" at the end of the javascript to tell it to expect a JSON Object, it will then convert the JSONString to a javascript Object automatically for you so the data parameter will be an onbect 请注意javascript末尾的"JSON" ,告诉它需要JSON对象,然后它将自动为您将JSONString转换为javascript对象,因此data参数将是一个onbect

Add Special characters at the end of each value and in jquery, using jquery split, cut the variable and display

like below;

$jsonData = '{"fare":30580^^,"actual_distance":1519^^,"city":"Islamabad^^","status":true}';

$json = json_decode($jsonData,true);
echo $json['fare'];


in jquery

function(data){
var tdata = data.split("^^");
            $('#fare').html(tdata[0]);
            $('#loading_spinner').hide();

        });

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

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