如何使用jquery ajax提供和获取数据?

Bol*_*sar 3 php mysql ajax jquery

我创建了一个jquery ajax请求,并尝试将一个变量传递给php来进行查询并将数据返回给实际的上下文.

处理ajax的实际上下文:

        $.ajax({
        type: 'post',
        url: 'show.php',
        data: {name: name},
        dataType: 'json',
        success: function(response) {
        //here I'd like back the php query
                    }
Run Code Online (Sandbox Code Playgroud)

PHP:

$hostelName = $_POST['name'];

$sql = //here is the actual sql containing the $hostelname

$query = mysql_query($sql);

$obj = mysql_fetch_object($query);
$sum = $obj->sum;
$tour = $obj->tour;


echo json_encode(
array(
    "sum" => $sum,
    "tour" => $tour
    )
);
Run Code Online (Sandbox Code Playgroud)

Kar*_*mar 6

试试这个:

    $.ajax({
    type: 'post',
    url: 'show.php',
    data: "name="+ name,
    dataType: 'json',
    success: function(response) {
    //here I'd like back the php query
    }
Run Code Online (Sandbox Code Playgroud)

和你的PHP代码:

    $hostelName =mysql_escape_string($_POST['name']);

    $sql = //here is the actual sql containing the $hostelname

    $query = mysql_query($sql);

    $reusult = mysql_fetch_assoc($query);
    echo json_encode($reusult);
Run Code Online (Sandbox Code Playgroud)