2010-11-11 31 views
13

Questo funziona bene:jQuery.ajax ritorna 400 Richiesta

jQuery('#my_get_related_keywords').click(function() { 
    if (jQuery('#my_keyword').val() == '') return false; 
     jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/" 
     +jQuery('#my_keyword').val()+"?" 
     +"appid=myAppID" 
     +"&lang=en" 
     +"&format=json" 
     +"&count=50" 
     +"&view=keyterms" 
     +"&callback=?", 
     function (data) {//do something} 

Ciò restituisce 400 Bad Request (solo una riformulazione di quanto sopra jQuery con Ajax per sostenere la gestione degli errori).

jQuery('#my_get_related_keywords').click(function() 
    { 
    if (jQuery('#my_keyword').val() == '') return false; 
    jQuery('#my_loader').show(); 
    jQuery.ajax(
     { 
     url: "http://boss.yahooapis.com/ysearch/web/v1/" 
     +jQuery('#my_keyword').val()+"?" 
     +"appid=myAppID" 
     +"&lang=en" 
     +"&format=json" 
     +"&count=50" 
     +"&view=keyterms" 
     +"&callback=?", 
     success: function(data) 
      {//do something} 
+0

devi aggiungere il metodo (post o ottieni) da qualche parte? – Jan

risposta

15

Penso solo bisogno di aggiungere altre 2 opzioni (contentType e dataType):

$('#my_get_related_keywords').click(function() { 

    $.ajax({ 
      type: "POST", 
      url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE", 
      data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}', 
      contentType: "application/json; charset=utf-8", // this 
      dataType: "json", // and this 
      success: function (msg) { 
       //do something 
      }, 
      error: function (errormessage) { 
       //do something else 
      } 
     }); 
} 
+0

Grazie per l'aiuto rapido Toro. @light era anche corretto. –

11

Aggiungi questo al vostro ajax chiamata:

contentType: "application/json; charset=utf-8", 
dataType: "json" 
+0

Grazie. Era così. @Toro ti ha appena battuto :) –

6

risposta tardi, ma ho pensato vale la pena tenerlo aggiornato Espansione sulla risposta di Andrea Turri per riflettere i metodi aggiornati di jQuery API e .success/.error deprecati.

A partire da jQuery 1.8. * Il modo migliore per farlo è utilizzare .done() e .fail(). Jquery Docs

ad es.

$('#my_get_related_keywords').click(function() { 

    var ajaxRequest = $.ajax({ 
     type: "POST", 
     url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE", 
     data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}', 
     contentType: "application/json; charset=utf-8", 
     dataType: "json"}); 

    //When the request successfully finished, execute passed in function 
    ajaxRequest.done(function(msg){ 
      //do something 
    }); 

    //When the request failed, execute the passed in function 
    ajaxRequest.fail(function(jqXHR, status){ 
     //do something else 
    }); 
}); 
Problemi correlati