php - php中的json对象没有被读取

标签 php jquery json mysqli

我想将 usernamepassword 传递给 php 脚本并检查数据库。在客户端,我使用以下脚本制作一个 json 对象 并将其发布到 php 文件。

var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();

var myjson = JSON.stringify(myobj);

$.ajax({
method: "POST",
url: "checkpass.php",
data: myjson
})
.done(function( msg ) {
    alert( msg );
});

在服务器端,当我在 firebug 中看到时,帖子被传递为

Parametersapplication/x-www-form-urlencodedDo not sort {"usrname":"XXXXXXX...
JSON

usrname "XX"

usrpass "justdoit" Source {"usrname":"XXX","usrpass":"justdoit"}

然而,当我运行 php 脚本来检查查询时,它返回一个错误

$usrname = $_POST['usrname'];
$usrpass = $_POST['usrpass'];

$sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
$result = $conn->query($sql);

if($result >0){
$output = 'Success';
} else
{
$output = 'fail';
}

我已经尝试过所有帖子,但无法正常工作。

提前致谢。

问候,

最佳答案

为了让ajax有一个成功的事件,回显并终止语句

Js File

 var myobj = {};

        myobj["usrname"] = 'myUsername';

        myobj["usrpass"] = 'myPassword';



        $.ajax({
            type: "post",
            url: "url",
            dataType: "json",
            data: {post_data: myobj},
            contentType: "application/x-www-form-urlencoded",
            success: function (responseData) {
                console.log(responseData);
            },
            error: function (errorThrown) {
                console.log(errorThrown);
            }
        });

PHP action File

           /** if we print post we will get the following array * */
//print_r($_Post);
//die()
//Array
//(
//    [post_data] => Array
//        (
//            [usrname] => myUsername
//            [usrpass] => myPassword
//        )
//
//)

if (isset($_Post['post_data'])) {
    $myPost = $_Post['post_data'];
    $usrname = $myPost['usrname'];
    $usrpass = $myPost['usrpass'];

    $sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
    $result = $conn->query($sql);
    $num_row = $result->num_rows;

    if ($num_row > 0) {
        $output = 'Success';
    } else {
        $output = 'fail';
    }
    echo json_encode($output);
    die();
}

关于php - php中的json对象没有被读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30161016/

相关文章:

php - 在 MYSQL PHP 中对城市、州和国家进行分组

php - 为什么这是 PHP 中的错误 MYSQL 查询?

javascript - Marionette.js CollectionView,只渲染特定模型

json - Angular 5 Observable映射到Json数组

java - 如何使用 jolt 库在列表中转换列表

php - 将基于网络的游戏嵌入到 Android 应用程序中

php - 我可以对不同的操作使用相同的 View 吗?

c# - 部分 View 刷新后保存数据的 jQuery 对话框

jquery - 仅在 inputmask jquery 中从特定号码开始验证电话号码

jquery - 使用JSONP跨域ajax请求json文件