La solicitud Ajax devuelve 200 OK, pero se dispara un evento de error en lugar de éxito


He implementado una solicitud Ajax en mi sitio web, y estoy llamando al punto final desde una página web. Siempre devuelve 200 OK, pero jQuery ejecuta el evento de error. Intenté muchas cosas, pero no pude entender el problema. Estoy agregando mi código a continuación:

Código jQuery

var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});
function AjaxSucceeded(result) {
    alert("hello");
    alert(result.d);
}
function AjaxFailed(result) {
    alert("hello1");
    alert(result.status + ' ' + result.statusText);
}

Código C # para JqueryOpeartion.aspx

protected void Page_Load(object sender, EventArgs e) {
    test();
}
private void test() {
    Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}

Necesito la cadena ("Record deleted") después de la eliminación exitosa. Soy capaz de eliminar el contenido, pero no estoy recibiendo este mensaje. Es esto correcto o estoy haciendo ¿pasa algo? ¿Cuál es la forma correcta de resolver este problema?

Author: K48, 2011-05-31

15 answers

jQuery.ajax intenta convertir el cuerpo de la respuesta dependiendo del parámetro dataType especificado o del encabezado Content-Type enviado por el servidor. Si la conversión falla (por ejemplo, si el JSON/XML no es válido), se activa la devolución de llamada de error.


Su código AJAX contiene:

dataType: "json"

En este caso jQuery:

Evalúa la respuesta como JSON y devuelve un objeto JavaScript. […] Los datos JSON se analizan de manera estricta; cualquier JSON malformado es rechazado y un análisis se lanza el error. [an] una respuesta vacía también es rechazado; el servidor debe devolver una respuesta de null o {} en su lugar.

Su código del lado del servidor devuelve un fragmento HTML con el estado 200 OK. jQuery esperaba un JSON válido y por lo tanto dispara la devolución de llamada de error quejándose de parseerror.

La solución es eliminar el parámetro dataType de su código jQuery y hacer que el código del lado del servidor devuelva:

Content-Type: application/javascript

alert("Record Deleted");

Pero preferiría sugerir devolver una respuesta JSON y mostrar el mensaje dentro de la devolución de llamada de éxito:

Content-Type: application/json

{"message": "Record deleted"}
 957
Author: Salman A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-18 14:26:23

He tenido algo de buena suerte con el uso de múltiples, separados por espacios dataType s ( jQuery 1.5+). Como en:

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'text json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});
 28
Author: jaketrent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-25 10:13:53

Simplemente tienes que eliminar el tipo de datos : "json" en tu llamada AJAX

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'json', //**** REMOVE THIS LINE ****//
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});
 24
Author: Philippe Genois,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-07 03:23:49

Esto es solo para que conste, ya que me encontré con este post al buscar una solución a mi problema que era similar a la de la OP.

En mi caso, mi solicitud jQuery Ajax no pudo tener éxito debido a política del mismo origen en Chrome. Todo se resolvió cuando he modificado mi servidor (Nodo.js) para hacer:

response.writeHead(200,
          {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "http://localhost:8080"
        });

Literalmente me costó una hora de golpearme la cabeza contra la pared. Me siento estúpido...

 14
Author: Corvin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-25 10:23:34

Creo que tu página aspx no devuelve un objeto JSON. Tu página debería hacer algo como esto (page_load)

var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);

Response.Write(OutPut);

También, trate de cambiar su AjaxFailed:

function AjaxFailed (XMLHttpRequest, textStatus) {

}

textStatus debería darte el tipo de error que estás recibiendo.

 12
Author: LeftyX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-09 07:28:13

Me he enfrentado a este problema con una biblioteca jQuery actualizada. Si el método service no devuelve nada, significa que el tipo devuelto es void.

Luego en su llamada Ajax por favor mencione dataType='text'.

Resolverá el problema.

 11
Author: Suresh Vadlakonda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-25 10:31:58

Solo tiene que eliminar dataType: 'json' de su encabezado si su método de servicio web implementado es nulo.

En este caso, la llamada Ajax no espera tener un tipo de datos de retorno JSON.

 5
Author: Bilel omrani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-25 10:18:38

Tuve el mismo problema. Mi problema era que mi controlador estaba devolviendo un código de estado en lugar de JSON. Asegúrese de que su controlador devuelve algo como:

public JsonResult ActionName(){
   // Your code
   return Json(new { });
}
 3
Author: Alexander Suleymanov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-25 10:20:25

Otra cosa que arruinó las cosas para mí fue usar localhost en lugar de 127.0.0.1 o viceversa. Aparentemente, JavaScript no puede manejar solicitudes de uno a otro.

 1
Author: Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-25 10:17:37

Utilice el siguiente código para asegurarse de que la respuesta está en formato JSON (versión PHP)...

header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
 1
Author: Terry Lin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-25 10:19:42

Yo tenía el mismo problema. Fue porque mi respuesta JSON contiene algunos caracteres especiales y el archivo del servidor no estaba codificado con UTF-8, por lo que la llamada Ajax consideró que esta no era una respuesta JSON válida.

 0
Author: Mehdi Izcool,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-25 10:31:19

Véase esto . También es un problema similar. Trabajando lo intenté.

No retire dataType: 'JSON',

Nota: echo solo formato JSON en archivo PHP si utiliza solo php echo su código ajax devuelve 200

 0
Author: Inderjeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-03 11:48:30

Tengo el problema similar, pero cuando intenté eliminar el tipo de datos:'json' Todavía tengo el problema. Mi error se está ejecutando en lugar del éxito

function cmd(){
    var data = JSON.stringify(display1());
    $.ajax({
        type: 'POST',
        url: '/cmd',
        contentType:'application/json; charset=utf-8',
        //dataType:"json",
        data: data,
        success: function(res){
                  console.log('Success in running run_id ajax')
                  //$.ajax({
                   //   type: "GET",
                   //   url: "/runid",
                   //   contentType:"application/json; charset=utf-8",
                   //   dataType:"json",
                   //   data: data,
                   //  success:function display_runid(){}
                  // });
        },
        error: function(req, err){ console.log('my message: ' + err); }
    });
}
 0
Author: Rakesh Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-09 01:08:18

Su script exige un retorno en el tipo de datos JSON.

Prueba esto:

private string test() {
  JavaScriptSerializer js = new JavaScriptSerializer();
 return js.Serialize("hello world");
}
 -1
Author: Kashif Faraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-21 05:10:01

Intenta seguir

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: { "Operation" : "DeleteRow", 
            "TwitterId" : 1 },
    dataType: 'json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

O

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow&TwitterId=1',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

Use comillas dobles en lugar de comillas simples en el objeto JSON. Creo que esto resolverá el problema.

 -10
Author: Salman Riaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-31 11:39:58