如何在页面上显示php发送的jsonp响应

时间:2015-11-14 08:21:36

标签: php jquery json ajax jsonp

我有一个jsonp的脚本如下

<script>
$(document).ready(function(){

    $("#LoginForm").submit(function(){

    var data = $(this).serialize();
    //alert(data);
    $.ajax({
            type:"POST",
            dataType:"jsonp",
            url:"https://akshay.tk/api/login.php",
            data:data,

            success:function(data)
            {       

                /// WHAT TO WRITE HER TO GET PHP RESPONSE
                /// DIV WHERE DATA TO BE SHOWN, ID IS RESULT    
            }

            });
    return false;
    });

});
</script>

我的php代码是

$username = $_REQUEST['username'];
$password = $_REQUEST['password'];              

// login check for user
$result = mysqli_query($con,"SELECT * FROM `admin_login` WHERE `username`='$username' AND `password`='$password'"); 

if(mysqli_num_rows($result) > 0) 
{
    $user = mysqli_fetch_assoc($result);
    // user found           
    $response["success"] = 1;
    $response["uid"] = $user["id"];
    $response["username"] = $user["username"];
    $response["role"] = $user["role"];

    echo json_encode($response);
}

一切都很顺利,当我使用开发人员工具时,我才知道它也给出了适当的回应。 通过php回复:

{"success":1,"uid":"1","username":"admin","role":"admin"}

我应该在jQuery SUCCESS函数中编写什么代码才能获得php响应?

2 个答案:

答案 0 :(得分:1)

如果你想输出php为你的ajax结果抛出的结果,那么

像这样创建一个div

success:function(data) { ('#yourDiv').html(data); }

然后在成功事件

<div class='yourDiv'></div>

注意:

如果您更喜欢上课,那么

('.yourDiv').html(data);

替换为

{"success":1,"uid":"1","username":"admin","role":"admin"}

其他数据:

最好像这样检查成功事件中的数据

当你将此作为回应时

success:function(data) { if(data.success==1) { ('#yourDiv').html('Welcome'+data.username); //You can append or do anything that you wish } else { ('#yourDiv').html.('Fail'); } }

/_(.*?)(?=\\)/g

答案 1 :(得分:0)

很多RND我都有答案 jQuery代码:

$("#submit").click(function(){

var myData = $("#LoginForm").serialize();

    $.ajax({
          method: "POST",
          dataType:"jsonp",
          url:"https://akshay.tk/api/login.php?callback=?",
          data: myData,

            success:function(msg)
            {
                alert(msg);                 
            }
        });

        return false;           
}); 

PHP代码略有变化。

if(mysqli_num_rows($result) > 0) 
            {
                $user = mysqli_fetch_assoc($result);
                // user found           
                $response["success"] = 1;
                $response["uid"] = $user["id"];
                $response["username"] = $user["username"];
                $response["role"] = $user["role"];

                echo $_GET['callback'] . '(' . json_encode($response) . ')';
            }

我工作了。我认为回调函数会将内部调用作为引用或其他内容,以便我们可以在跨域上工作

谢谢