来自客户端的回调不起作用


Callback from client-side not working

>我有html文件客户端(跨平台应用程序的一部分)进入php文件,需要获取变量或字符串,它正确地发布数据但没有接收回来。

这是在提交时触发的(客户端.html):

 var $form = $( this ),
         $submit = $form.find( 'button[type="submit"]' ),
         username_value = $form.find( 'input[name="username"]' ).val(),
         password_value = $form.find( 'input[name="password"]' ).val(),
         url =  $form.attr('action');
     /* Send the data using post */
      $.post(url, {username: username_value, password: password_value},function (data) {
        alert(data);
    });

这是 PHP 文件:

<?php
$username   = $_POST['username'];
$password   = $_POST['password'];
$DBusername = 'root';
$DBpassword = '';
$project = mysql_connect('localhost',$DBusername, $DBpassword);
mysql_select_db('PickMeUpDatabase', $project);
$sql="SELECT * FROM users WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);

if($count==1){
echo 'console.log("hi");'; 
        $message = "saved successfully";
        echo $message;
}
else
{
    $sql = "Insert into users Values('me','myself','I','".$username."','Irene')";
mysql_query($sql);
        echo "Helooo";
}
    ?>

我知道 php 文件在这一点上没有意义,我为调试更改了很多,但是"else"语句中的 mysql 查询正在传递并添加到数据库中,但它下方的回声没有返回到它将在 html 中发出警报的位置。实际上,我可以更改html中的警报以提醒任何事情,并且不会发生。

发生这种情况的原因

可能有很多。

您是否打开了错误报告?如果没有,请将其放在 php 分隔符之后:

ini_set( "display_errors", true );

另外,数据是否跨域发送?把它放在上面一行之后,

 header('Access-Control-Allow-Origin: *');

现在,它可能是 POSTing,但这并不一定意味着数据在服务器端可用。每当我在 JQuery 中使用 post() 函数时,我更喜欢数据参数的字符串。看起来也有一些变量是未定义的。

所以我会这样重写它:

 var $form = $( this ),
         $submit = $form.find( 'button[type="submit"]' ),
         username_value = $form.find( 'input[name="username"]' ).val(),
         password_value = $form.find( 'input[name="password"]' ).val(),
          /* Turn the variables into strings- for simplicity! */
         url =  "http://localhost/location/of/php_file.php";

      var data='username='+username_value+'&password='+password_value;
      $.post(url, data, function (data) {
        alert(data);
    });

那应该再清理一下。