获取由ajax函数调用的php页面中的参数

时间:2012-08-31 13:04:38

标签: php jquery ajax parameter-passing

我使用jquery和ajax调用php页面res.php。代码是: -

$('#submit_button').click(function () {        
    buildingVal = $("#building");
    levelVal = $("#level");
    data = 'building=' + buildingVal.val() + 'level=' + levelVal.val();
    $.ajax( {

        url: "res.php", 
        type: "POST",
        data: data,     
        success: function (data) {
            $('#npc').html(data);
        }
    });​
});

res.php页面代码为: -

<?php
//connect to the database
$con = mysql_connect("localhost","root","12345") or die("error ".mysql_error());

//connect to the travian table
mysql_select_db("trav",$con) or die("error ".mysql_error());

$building = mysql_real_escape_string($_GET['building']);
$level = mysql_real_escape_string($_GET['level']);


$query = "select * from ";
$query = $query . $building;
$query = $query . "where lvl=" . $level;
$query = $query . ";";
$result = mysql_query($query) or die('Error in Child Table!');

$data = mysql_fetch_assoc($result);

echo '<table><tr><td>Lumber=$data["lumber"]</td><td>Clay=$data["clay"]</td><td>Iron=$data["iron"]</td><td>Crop=$data["crop"]</td>';

?>

我收到错误

Notice: Undefined index: building in C:\xampp\htdocs\debal\res.php on line 8

Notice: Undefined index: level in C:\xampp\htdocs\debal\res.php on line 9
Error in Child Table!

如何提取发送到页面的参数并在sql查询中使用它们从数据库中的表中检索数据。 请你能帮帮我..

1 个答案:

答案 0 :(得分:4)

问题是你是通过AJAX发送$ _POST值并尝试在res.php页面上从$ _GET中分配变量。将AJAX函数更改为type: "GET"

$building = mysql_real_escape_string($_POST['building']);
$level = mysql_real_escape_string($_POST['level']);

on res.php

你也没有正确发送'level'变量,你错过了'&amp;'

data = 'building=' + buildingVal.val() + '&level=' + levelVal.val();