使用jquery使用ajax发送和接收参数

时间:2013-08-22 08:41:32

标签: php jquery ajax

我想在没有任何成功的情况下使用AJAX发送和接收参数

首先,我选择AREA而不是该地区的CITIES。

你能告诉我我做错了吗?

客户方:

<script>
$(document).ready(function(){

  $("#first").click( 

    function(){

        var area_id=$("#area_id").val();

        $.ajax({
        type: "POST",
        url: "recs.php",
        data: "area_id="+area_id,
        cache:false,
        success: 
          function(data){
            $("#second").html(data.message); 
          }

        });

      return false;

    });


});


</script>


<form method="post" action="tosomewhere.php">

    <select id="first" name="area_id">
      <option value="1">1</option>
      <option value="2">2</option>
    </select>

    <select id="second" name="section">  </select>

</form>

服务器端:

$areaID = $_POST['area_id'];
$second_option = "";

$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = $areaID ORDER BY id ASC");
while($index = mysql_fetch_array($query2)) 
{
    $id = $index['id'];
    $name  = $index['name'];

    $second_option .= "<option value='$id'>$name</option>";
}

echo $second_option;
exit;

先谢谢你

编辑后:

我将代码更改为更简单的代码:

客户方:

<script>
$(document).ready(function(){
  $("#first").click( 
    function(){
        var area_id=$("#area_id").val();

        $.ajax({
        type: "GET",
        url: "recs.php",
        data: "area_id="+area_id,
        cache:false,
        success: 
          function(data){
            $("#second").html(data); 

          }

        });

      return false;

    });


});


</script>

<form method="post" action="tosomewhere.php">

    <select id="first" name="area_id">
      <option value="1">1</option>
      <option value="2">2</option>
    </select>

    <div id="second"></div>

</form>

服务器端:

some text

我仍然没有将字符串输入

4 个答案:

答案 0 :(得分:3)

变化

$("#second").html(data.message); 

$("#second").html(data); 

答案 1 :(得分:0)

无论你的ajax调用是否实际初始化,你都需要调试实际出错的代码。

i:检查值是否正确获取“area_id”js变量

alert(area_id);

ii:如果可以,请检查服务器脚本中是否正确返回数据

alert(data); or alert(data.message);

iii:为了测试您是否正确接收数据,只需发送测试脚本。

echo "sample text";
exit;

或尝试以json格式发送数据

die('{"message" : "sample text"}');

如果所有三个步骤都有效,那么数据访问脚本应该有错误。

如果您没有在ajax中获得输出,请尝试使用firebug检查发送请求和获取响应时实际发生的情况。

答案 2 :(得分:0)

<script>
$(document).ready(function(){
  $("#first").click(function(){
        var area_id=$("#area_id").val();
        $("#second").load('tosomewhere.php?area_id=' + area_id);
      return false;
    });
});
</script>

稍微更改了jquery。使用GET。

脚本也改变了:

$areaID = (int) $_GET['area_id'];
$second_option = "";

$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = '$areaID' ORDER BY id ASC");
if (mysql_num_rows($query2) > 0){    
    while($index = mysql_fetch_array($query2)){
        $second_option .= '<option value="'.$index['id'].'">'.$index['name'].'</option>';
    }
    echo $second_option;
} else {
    echo 'No result!';
}

die();

在$ _GET之前添加(int)作为安全前测量。

答案 3 :(得分:0)

将此参数添加到ajax函数

dataType:'text'
相关问题