无法在非jQuery函数中使用jQuery post的问题 [英] Trouble using jQuery post inside non jQuery function
问题描述
我在HTML页面中有以下脚本:
I have the following script inside a HTML page:
<script>
function Test(){
alert("i got here");
var username = document.registration_form.username.value;
alert(username);
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if (data = "0"){
alert('That username is already in use, please choose another');
return false;
};
if (data = "1") {
return true;
};
});
};
</script>
如果数据库中已经有用户名,我正在尝试进行功能测试以返回true或false.
I'm trying to get the function test to return true or false if a username is already in my database.
checkname.php包含以下内容:
checkname.php contains the following:
<?
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['name'];
$sql="SELECT * FROM members WHERE username='".$myusername."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count >= 1){
echo "0";
}
else {
echo "1";
}
?>
我已经尝试过对名称进行硬编码并运行PHP,并且效果很好.
I've tried hardcoding a name and running the PHP and it works fine.
尽管出于某种原因,当我运行Test()时,前2个警报运行正常,向我显示了已设置的用户名,但随后的警报均未显示.
For some reason though when I run Test() the first 2 alerts come through fine, showing me the username enetered, but none of the subsequent alerts appear.
Oooo和jQuery已添加到标题中,如下所示:
Oooo and jQuery has been added in the header like so:
<script src="create/js/jquery-1.4.4.min.js" type="text/javascript" ></script>
<script src="create/js/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>
任何帮助,不胜感激:)
Any help much appreciated :)
推荐答案
首先,从回调到$ .post的return语句将 not 从Test()函数返回.您应该使用处理服务器中数据的回调函数来调用Test,如下所示:
First of all, your return statements from the callback to $.post will not return from your Test() function. You should call Test with a callback function that deals with the data from the server, something like this:
function Test(username, callback) {
$.post("checkname.php", {name: username}, callback);
}
Test(document.registration_form.username.value, function(data) {
if(data == "0") {
// Do something
} else {
// Do something else
}
});
布拉德在比较方面也是正确的-您当前为数据分配了"0".我认为,即使有其他错误,您也应该收到警报.也许您需要checkname.php脚本的绝对路径?例如. "/checkname.php"(注意斜线)?
Brad is also correct about the comparison - you're currently assigning "0" to data. You should get the alerts though, I think, even with the other errors. Maybe you need the absolute path to the checkname.php script? E.g. "/checkname.php" (note the slash)?
这篇关于无法在非jQuery函数中使用jQuery post的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!