2012-07-20 94 views
2

從AJAX處理表單時出現奇怪的問題。jQuery AJAX發送數據但會觸發錯誤

它按預期工作,但由於某種原因,它引發了一個錯誤而不是成功。

這是代碼:

$(".sendBtn").click(function(e) { 

    campaigncode = "#####"; 
    senderemail = "[email protected]"; 
    subject = "Test"; 
    sendermessage = "Test"; 
    targetURL = "www.abc.com"; 

    email = $(".email").val(); 

    //Email Validation 
    var emailReg = /^([\w-\.][email protected]([\w-]+\.)+[\w-]{2,4})?$/; 
    if(email ==""){//Empty Check 
     alert('Please enter your email'); 
     e.preventDefault(); 
    } else { 
     if(!emailReg.test(email)) {//Email validation 
      alert('*Please enter valid email'); 
      e.preventDefault(); 
     } else { 

    //Ajax Start 
    $.ajax({ 
      url: "http://services.ninemsn.com.au/sendtofriend/sendtofriendService.aspx?showdefaultmessage=true", 
      context: document.body, 
      type: "POST", 
      data: {campaigncode:campaigncode, recipientemail:email, senderemail:senderemail, subject:subject, sendermessage:sendermessage, targetURL:targetURL}, 
      dataType: "jsonp", 
      success: function() { 
       alert('Success'); 
      }, 
         error: function() { 
            alert('Error'); 
           } 

     });//Ajax End 

     } 
    } 

}); 
+3

AJAX事件是從同一個域還是跨域激發的? – 2012-07-20 02:29:38

+0

來自跨域的火災,但它的工作原因,我可以收到電子郵件,但只是提醒錯誤 – Dips 2012-07-20 02:34:11

+0

猜測他的網站不是ninemsn,所以它是跨域。 @PraveenKumar然而它是JSONP,它是爲跨域設計的。 – Scotty 2012-07-20 02:34:15

回答

2

從你的錯誤,看起來像this questionthat question是相似的。 「jQuery_172blah未被調用」錯誤指的是jsonp回調(因爲解析某處失敗,所以未調用該回調)。我建議......

  1. 嘗試設置crossDomain: true,然後還要設置dataType:textdataType:text json
  2. 嘗試通過data作爲字符串而不是字典。
  3. 嘗試設置jsonp:falsejsonpCallback。關於這些,請參閱documentation

例如:

var jsonString = JSON.stringify({ 
    recipientemail: email 
}); 
$.ajax({ 
    url: "http://services.ninemsn.com.au/sendtofriend/sendtofriendService.aspx?", 
    crossDomain: true, 
    dataType: 'text json', 
    data: jsonString, 
    ... 
+0

但使用'dataType:'文本json','不發送數據 – Dips 2012-07-20 03:04:58

+0

@Dips:嘗試將'data'作爲JSON字符串傳遞,請參閱上面的建議。 – Scotty 2012-07-20 03:22:26

+0

沒有進展。還是同樣的問題 – Dips 2012-07-20 03:37:00

0

JSONP要求響應被包裹在某種回調函數。

嘗試登錄到控制檯的反應,看看有什麼被送回

success: function(data) { console.log(data); } 

另外,儘量包住響應轉換成使用$ .parseJSON對象:

success: function(data) { 
    var json = $.parseJSON(data); 
} 
0

的錯誤是在服務器發送「response.allowGet」