php - 从 php 传递到 AJAX

标签 php ajax jquery

是否可以将两个变量从 PHP 传递到 AJAX 并单独使用它们:

获取这个:

echo $row['route'] + $row['Distance'] ;

然后我可以:

$.getJSON("DisplayIndividualMySQLi.php", function(data) { 
    // alert(route);
    // alert(distance);
     }

最佳答案

当您使用 getJSON 从 php 获取数据时,来自 php 的响应需要采用 json

http://php.net/manual/en/function.json-encode.php

<小时/>

PHP

// DB Query to set $row[ 'route' ] and $row[ 'Distance' ]
$sql = "SELECT route, Distance, UserID, RandomField, Etc FROM foo where bar = 'baz' LIMIT 1";
$row = $db->query( $sql )->fetch_assoc();
//...

$array = array( 
    'route' => $row[ 'route' ],
    'distance' => $row[ 'Distance' ],
    'UserID' => $row[ 'UserID' ]
);
// returns { "route": "foo", "Distance": "bar", "UserID": "User" }
echo json_encode( $array );
<小时/>

JS

// Case is important on things in the data object!
$.getJSON( "DisplayIndividualMySQLi.php", function( data ) {
   console.log( data ); // Object
   console.log( data.route ); // shows php's $row[ 'route' ]
   console.log( data.Distance ); // shows php's $row[ 'Distance' ]
} );

关于php - 从 php 传递到 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14347055/

相关文章:

ajax - 在 Coldfusion 中保护远程 CFC

jquery - 使用 css 样式而不是 jQuery

jquery - 使用 ember.js 和 ember easyform 包装 bootstrap/jquery 小部件

ajax - 将参数传递给 jQuery 数据表中的 sAjaxSource

javascript - 如何使用我的后端从客户端 JS 发送电子邮件

php - Yii,我正在尝试为我的 View 设置一个动态布局

php - 如何使用php检查mysql更新语句的错误?

javascript - 用于拖放绘图应用程序的 Canvas 与 jQuery

php - 无法从查询中获取值

php - 如何检查 'http://' 是否在变量中,如果没有,添加它?