【发布时间】:2016-03-10 19:43:40
【问题描述】:
我有一个 javascript 函数,它根据使用的浏览器创建一个 XMLHttpRequest 对象或 ActiveObject,该浏览器位于一个名为 ajax.js
的文件中HTML: user.php
<ul id="list-of-developers">
<li class="list-title"><strong data-new-link="true">DEVELOPERS</strong>
</li>
</ul>
JAVASCRIPT:ajax.js
function ajaxObj2(meth, url, contype){
var xhttp;
if (window.XMLHttpRequest)
{
xhttp = new XMLHttpRequest();
}
else
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open(meth, url, true);
xhttp.setRequestHeader("Content-type",contype);
xhttp.setRequestHeader("Access-Control-Allow-Origin", "http://localhost:9000/");
return xhttp;
}
function ajaxReturn(x){
if(x.readyState==4 && x.status ==200)
{
return true;
}
}
在我的 user.php 文件中,该文件包含我的 html 和脚本标记,包括文档头部的 ajax.js 文件。
以下是 javascript 与 PHP 的连接方式(注意:此标签位于文档底部的 body 标签之外)
JAVASCRIPT:user.php(内联)
<script>
window.onload = function()
{
var u = "<?= $u ?>";
var r = "<?= $user_role ?>";
var x = ajaxObj2('GET', 'retrieveDevelopers.php','text/plain');
x.onreadystatechange = function()
{
alert("H u is: "+u+ " r is: "+r + " RESPONSE: " + x.responseText.trim());
if(ajaxReturn(x) ==true)
{
alert("got here");
var list_of_devs = document.getElementById("list-of-developers");
console.log(list_of_devs);
list_of_devs.innerHTML = x.responseText.trim();
}
}
console.log(u);
x.send("u="+u + "&r="+r);
}
</script>
PHP:在retrieveDevelopers.php中
<?php
$x = $_GET["u"];
$m = $_GET["r"];
if(isset($_GET["u"]))
{
include_once("phpincludes/db_connx.php");
//echo
$person= preg_replace('#[^a-z0-9]#i','',$_GET["u"]);
$person_sql = "SELECT * FROM USERS WHERE USER_ID=(?) AND ACTIVATED=(?)";
$person_params = array($person, 1);
$person_options = array("Scrollable" => SQLSRV_CURSOR_CLIENT_BUFFERED);
$person_result = sqlsrv_query($db_connx, $person_sql,$person_params, $person_options);
$person_state = sqlsrv_num_rows($person_result);
if($person_state < 1)
{
echo "Failed to verify user";
exit();
}
else
{
echo("It Worked");
exit();
}
}
echo "failed";
exit();
?>
我收到错误“注意:未定义索引:第 9 行中的 u”和“注意:未定义索引:第 10 行中的 r”
我不明白这是为什么。数据库连接没有问题。 除了数据库连接脚本之外,这些文件都在同一个文件夹中
文件系统:
- /retrieveDevelopers.php
- /user.php
- /phpincludes.php/db_connx.php
- /script/ajax.js
系统信息
Apache Version:2.4.17
PHP Version: 5.6.15
MICROSOFT SQL SERVER 2012
Localhost: localhost:9000
【问题讨论】:
-
Get 在 URL 中而不是在发送函数中。您的网址应类似于
retrieveDevelopers.php?u="+u + "&r="+r -
查看 ajaxObj2() 函数,该函数将创建 url 值:"retrieveDevelopers.php?u=value&r=value"。
-
只需使用浏览器的调试器来查看您的 ajaxObj2 是否发送所需的值。然后你就会知道在哪里寻找错误,客户端或服务器端
-
我已经这样做了,响应是 (user.php:138 XHR 完成加载: GET "localhost:9000/retrieveDevelopers.php?")。没有错误,所有文件加载都没有问题。
标签: javascript php html sql-server ajax