【问题标题】:Jquery jsonp ajax callback not workingJquery jsonp ajax回调不起作用
【发布时间】:2014-08-14 04:41:15
【问题描述】:

我正在研究一个使用 jquery ajax 实现 jsonp 的示例。

谁能解释一下为什么回调函数'customcb'在下面的例子中没有被调用,我很困惑。

从客户端应用程序对 ASP.NET MVC 服务器应用程序进行 $.ajax 调用,下面是客户端代码

$().ready(function () 
{

 $.ajax({
 url: 'http://localhost:55632/',
 type: 'GET',
 dataType: 'jsonp',
 jsonp: 'cbqs',
 jsonpCallback: 'customcb',
 success: function (data) 
 {
 alert('success');
 },
 error: function (XMLHttpRequest, textStatus, errorThrown) 
 {
  alert(errorThrown);
 }
 });

 function customcb() 
 {
  alert('customcb');
  }

});

下面是用服务器应用程序编写的简单 ASP.net MVC 操作

public class HomeController : Controller
{
public string Index()
{
 Emp x = new Emp
 {
  fname = "first name",
  lname = "last name"
 };

 string json = JsonConvert.SerializeObject(x);
 Response.ContentType = "application/x-javascript";
 string str = "customcb(" + json + ")";
 return str;
 }
..............
..............

预期结果:应显示“成功”和“自定义”警报消息。

实际结果:仅显示“成功”警报消息。

注意:我可以访问成功函数返回的数据,并且没有 JS 错误。

请告诉我为什么没有显示“customcb”警报消息。

【问题讨论】:

    标签: jquery ajax jsonp


    【解决方案1】:

    将jsonpCallback函数移出“$().ready(function()”代码块。

    function customcb() 
    {
        alert('customcb');
    }
    

    【讨论】:

      【解决方案2】:

      由于您正在处理 jsonp,因此来自服务器的响应应该是以下形式:

      customcb({<JSON content>});
      

      你的 jsoncallback 应该是:

      function customcb( o ) {
          console.log( o );
      }
      

      【讨论】:

      • 我已经签入了 fiddler,repsonse 是 customcb({"fname":"first name","lname":"last name"}),所以我想这不是问题
      猜你喜欢
      • 2014-09-10
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      相关资源
      最近更新 更多