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

How to show jsonp response sent by php on a page

我有一个 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 响应?

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

像这样创建一个 div

<div id='yourDiv'></div>

然后在成功事件里面

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

注:

如果你喜欢class那么

<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');
    }
    }

很多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) . ')';
            }

它奏效了。我认为回调函数在内部被调用作为参考或其他东西,所以我们可以在跨域上工作

谢谢