是否可以将两个变量从 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/