簡體   English   中英

jQuery jsonp ajax回調不起作用

[英]Jquery jsonp ajax callback not working

我正在研究使用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;
 }
..............
..............

預期結果:應該同時顯示“成功”和“ customcb”警報消息。

實際結果:僅顯示“成功”警報消息。

注意:我能夠從成功函數訪問返回的數據,並且沒有JS錯誤。

請讓我知道為什么未顯示“ customcb”警報消息。

將jsonpCallback函數移出“ $()。ready(function()””代碼塊。

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

由於您正在處理jsonp,因此來自服務器的響應應采用以下形式:

customcb({<JSON content>});

並且您的jsoncallback應該是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM