2010-11-11 20 views
13

Esto funciona bien:jQuery.ajax devuelve 400 Bad Request

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} 

Esto devuelve 400 Bad Request (Sólo una reformulación de los anteriores jQuery usando ajax para apoyar la gestión de errores).

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

¿tiene que agregar el método (publicar o obtener) en algún lugar? – Jan

Respuesta

15

Creo que sólo tiene que añadir 2 opciones más (contentType y 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

Gracias por la ayuda rápida de Toro. @light también fue correcto. –

11

Agregue esto a su ajax llamada:

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

Gracias. Eso fue todo. @Toro simplemente te ganó :) –

6

respuesta tardía, pero supuse vale la pena mantener esto actualizado. Ampliando la respuesta de Andrea Turri para reflejar los métodos desactualizados de jQuery API y .success/.error.

A partir de jQuery 1.8. * La forma preferida de hacerlo es usar .done() y .fail(). Jquery Docs

p.

$('#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 
    }); 
}); 
Cuestiones relacionadas