如何使用来自php的响应到jquery中的$ .post()

时间:2013-06-09 12:05:26

标签: php jquery ajax

这是我在stackoverflow的第一个问题,具体说来......我正在使用我的PHP文件的结果(“myphp.php”)......

<?php
echo "Hello"
?>

现在调用的javascript代码:

function functionX()
{

var result;
$.post("myphp.php",function(data)
{
result=data; /// result should be Hello
});
alert(result); /// the msgbox shows "Undefined"
// i am enable to access the result i got from PHP file
}

所以我的问题是如何访问结果,以便我可以在我的代码的其他部分使用它... 或者你可以提出其他一些方法...... THANXX

因为我是ajax的新手..我想用这个概念检查用户名可用性如图所示

var result;
function functionX(username)
{

$.post("check_username.php",{usn:username},function(data)
{
if(data=="OK"){result="yes";}
if(data=="FAIL"){result="no";}
});
alert(result); // Now i want the result here .. its important
}

<?php
$usn=$_POST['usn'];
$flag=0;
$q=mysql_query("SELECT * FROM accounts");
while($row=mysql_fetch_assoc($q))
{
if($row['usn']==$usn)
{
$flag=1;break;
}
}
if($flag==1)
{
echo "OK";}
else
echo "FAIL";
?>

我知道这些用于检测用户名存在的方法可能很愚蠢..这就是我所做的

2 个答案:

答案 0 :(得分:0)

这是因为如果你只是把代码放在下面,那就不像raina77ow提到的那样。

如果以后不需要数据,请使用:

function functionX(){
  $.post("myphp.php",function(data)    {
    alert(data);
  });
}

答案 1 :(得分:0)

试试这个

var result;

$.ajax({
       type: "POST",
       url: 'myphp.php',
       success: function (data) {
           result=data;
       }

});​
alert(result);