Ajax没有传输正确的参数

时间:2015-02-02 06:23:40

标签: php jquery ajax

我正在尝试发出一个ajax请求但是我要发送的参数没有传输好。所以我有 user.php的

<script>
function showUser(str) {

  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  } 
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  document.write(str);
  xmlhttp.open("GET","getuser.php?q="+str,true);
  xmlhttp.send();
}
</script>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">John Smith</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>

这似乎正确地检索了值。如果我选择Joseph Swanson,则显示3即可。但是当我去getUser.php

<?php
$q = intval($_GET['q']);
var_dump($q);
?>

我每次都得到int 0。 有什么问题?

2 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为当您正在访问该页面时,查询字符串中没有类似q的内容。添加 -

if (!empty($_GET['q'])) {
  $q = intval($_GET['q']);
  var_dump($q);
}

现在只有在url中获取参数时才会显示。

答案 1 :(得分:0)

在分配为intval之前检查该值是否为数字。这是来自PHP documentation

  

返回值

     

成功时var的整数值,或失败时为0。空数组   返回0,非空数组返回1.

     

最大值取决于系统。 32位系统有最大值   有符号整数范围-2147483648到2147483647.例如on   这样的系统,intval('1000000000000')将返回2147483647   64位系统的最大有符号整数值是   9223372036854775807。

     

字符串很可能会返回0,尽管这取决于   字符串最左边的字符。整数转换的通用规则   应用

我建议使用JQuery代替AJAX,在学习时更容易掌握。

//add JQuery//
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function showUser(str) {
    $(function() {
        $.ajax({
            url: "/getuser.php", //assumes file is in root dir//
            type: "post",
            data: "q="+str,
            processData: false,
            success: function(response) {
                alert ("processed"); //alerts that PHP processed the request//
                $("#txtHint").html(response); //inserts echoed data into div//
            }
        });
    });
}
</script>

然后在PHP文件中,尝试添加...

echo $_POST['q'];
exit;

这至少会告诉你他们在说话。但它不会在屏幕上显示,您需要查看开发人员工具 - &gt;网络 - &gt;响应(但也应该在#txtHint)。如果您收到回复,请立即尝试。

编辑:
还要检查开发人员工具中的网络选项卡,以确保发送请求。