简体   繁体   中英

How to log AJAX posted data?

Is there a way to log AJAX posted URL and data? I tried many ways with mixed success. I appreciate your help. The code I tried is below:

$.ajax({
  type: 'POST',
  url: 'mylink',
  data: {
    id: 123, 
    name: John
  },
  dataType: 'json',
  error: function(req, err) { 
    console.log('my data' + url + data); 
  }
});

write the console.log() before the ajax call.

By the way, john, in the data needs apostrophes ( "john" )

You can't get those values back out of the $.ajax call, it doesn't create an object which contains that information. So you need to create that ability yourself. One way to make this easy would be to define your AJAX options outside the actual function call, and assign them to a variable which you can re-use and log values from:

var ajaxOptions = {
    type: 'POST',
    url: 'mylink',
    data: {id:123, name: "John"},
    dataType: 'json'
}
console.log('my data: ' + ajaxOptions.url + ' ' + JSON.stringify(ajaxOptions.data));
$.ajax(ajaxOptions);

That example logs the data every time, before the AJAX call starts. You could of course choose instead to do the logging only if there's an error, similar to your original version:

$.ajax(ajaxOptions).fail(function(jqXHR, textStatus, errorThrown) {
  console.log('my data: ' + ajaxOptions.url + ' ' + JSON.stringify(ajaxOptions.data));
});

You might want to also consider logging the error information at the same time...

在向数据对象添加属性或值时,您可以在函数内部但在 ajax 之上进行 console.log

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM