简体   繁体   English

jQuery jsonp ajax回调不起作用

[英]Jquery jsonp ajax callback not working

I am working on a sample example of implementing jsonp using jquery ajax . 我正在研究使用jquery ajax实现jsonp的示例示例。

Can someone please explain why the callback function 'customcb' is not getting invoked in below example , am confused. 有人可以解释为什么在下面的示例中未调用回调函数'customcb'感到困惑。

From client application am making an $.ajax call to an ASP.NET MVC server application, below is the client code 从客户端应用程序对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');
  }

});

And below is the simple ASP.net MVC action written in server application 下面是在服务器应用程序中编写的简单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;
 }
..............
..............

Expected Result: Both 'success' and 'customcb' alert messages should be displayed. 预期结果:应该同时显示“成功”和“ customcb”警报消息。

Actual Result : Only 'success' alert message is getting displayed. 实际结果:仅显示“成功”警报消息。

Note : I am able to access the returned data from success function and there are no JS errors. 注意:我能够从成功函数访问返回的数据,并且没有JS错误。

Please let me know why 'customcb' alert message is not getting displayed. 请让我知道为什么未显示“ customcb”警报消息。

Move the jsonpCallback function out of "$().ready(function ()" code block. 将jsonpCallback函数移出“ $()。ready(function()””代码块。

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

Since you're dealing with jsonp your response from the server should be of the form: 由于您正在处理jsonp,因此来自服务器的响应应采用以下形式:

customcb({<JSON content>});

And your jsoncallback should be: 并且您的jsoncallback应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM