jQuery + Ajax,Params有数据,但是响应说没有数据 [英] Jquery + Ajax, Params has data but response says no data

查看:94
本文介绍了jQuery + Ajax,Params有数据,但是响应说没有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下脚本:

$("#spid").blur(function() {
    $.ajax({
       url: 'getsponsor.php',
       type: "POST",
       dataType:'json',
       data: ({ spid: $("#spid").val() }) ,
       contentType: 'application/json; charset=utf-8',
       success: function (result) {
           $("#sponname").text(result);
       },
       error: function () {
           $("#sponname").text("Cannot fetch the sponsor name.");
       }
   }); 
});

注意:#sponname是一个标签.

Note: #sponname is a label tag.

以下是getsponsor.php的php代码:

Following is the php code of getsponsor.php:

if(!isset($_POST['spid']) || empty($_POST['spid']))
    echo json_encode("No Data");
else {
    $spid=$_POST['spid'];
    $stmt = $con->prepare("SELECT name FROM users WHERE id=?");
    $stmt->bind_param("s",$spid);
    $stmt->execute();
    $stmt = $stmt->get_result();
    if ($stmt->num_rows >0) {
        $row = $stmt->fetch_object();
        echo json_encode($row->name);
    }
    else {
        echo json_encode("No Records");
    }
}

当我检查页面并转到 Network-> Params 时,我会从文本框中获得正确的值:

When I Inspect the page and goto Network->Params, I get the right value from the textbox:

spid = 1125468

spid=1125468

但是,当我转到网络->响应时,会收到以下消息

But, when I go to Network->Response, I get the following message

无数据"

请告诉我我在做什么错?

Please tell what wrong I am doing?

推荐答案

摆脱这一行:

contentType: 'application/json; charset=utf-8',

正在将数据发送为URL编码,而不是JSON.jQuery会自行发送正确的Content-type标头.

The data is being sent URL-encoded, not as JSON. jQuery will send the correct Content-type header by itself.

这篇关于jQuery + Ajax,Params有数据,但是响应说没有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆