2017-10-08 2 views
1

Ich habe Probleme bei der Implementierung jQuery AJAX mit JSON Antwort. Ich versuche, darauf zuzugreifen, aber meine fehlgeschlagene Rückruffunktion wird aufgerufen. Ich möchte, dass meine Erfolgsrückruffunktion aufgerufen wird.Implementieren von jQuery AJAX mit JSON Antwort

Beachten Sie auch, dass auf plain JavaScript ich habe es bereits implementiert und ich weiß über Jsonp und Cross-Domain-Ajax Fundas. Es auf jQuery, wo ich versage.

Die JSONP Lage - here

Der Code ist:

   $.ajax({ 
       url: "http://www.demo.yogihosting.com/jquery/jsonp/data1.json", 
       dataType: "jsonp", 
       type: "POST", 
       contentType: "application/json; charset=utf-8", 
       success: function (result, status, xhr) { 
        alert(result); 
       }, 
       error: function (xhr, status, error) { 
        alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) 
       } 
      }); 

du auf jQuery AJAX with jsonp on CodePen anzeigen können.

Bitte helfen!

+0

Können Sie Ihre fehlgeschlagene Rückruffehlermeldung posten? –

+0

@SamDev ich versuche, jsonp Antwort von localhost zu holen, und ich bekomme diesen Fehler - 'jQuery31006235097177340809_1507490891841 wurde nicht 200 laden' – yogihosting

+0

versuchen Sie mit dataType: "JSON" –

Antwort

1

Das JSONP Format Sie aufrufen hat einen Rückruf von processJSONPResponse, so müssen Sie, dass in der jsonpCallback Parameter Ihrer AJAX-Anforderung setzen:

$(document).ready(function() { 
    $("#jsonpButton1").click(function(e) { 
    $.ajax({ 
     url: "http://www.demo.yogihosting.com/jquery/jsonp/data1.json", 
     dataType: "jsonp", 
     type: "POST", 
     jsonpCallback: 'processJSONPResponse', // add this property 
     contentType: "application/json; charset=utf-8", 
     success: function(result, status, xhr) { 
     console.log(result); 
     }, 
     error: function(xhr, status, error) { 
     console.log("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) 
     } 
    }); 
    }); 
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<button id="jsonpButton1">Button 1</button> 

Working example

Beachten Sie, dass ich musste das Arbeitsbeispiel in eine Geige legen, da SO keine unsicheren abgehenden Anfragen erlaubt.

+0

Vielen Dank, es hat perfekt funktioniert - jsonpCallback: 'processJSONPResponse' war das Ding, das in meinem Code fehlt. – yogihosting