简体   繁体   English

如何记录 AJAX 发布的数据?

[英]How to log AJAX posted data?

Is there a way to log AJAX posted URL and data?有没有办法记录 AJAX 发布的 URL 和数据? 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.ajax调用之前编写console.log()

By the way, john, in the data needs apostrophes ( "john" )顺便说一句,约翰,在数据中需要撇号( "john"

You can't get those values back out of the $.ajax call, it doesn't create an object which contains that information.您无法从 $.ajax 调用中取回这些值,它不会创建包含该信息的对象。 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:简化此操作的一种方法是在实际函数调用之外定义 AJAX 选项,并将它们分配给一个变量,您可以重用该变量并记录以下值:

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.该示例每次都在 AJAX 调用开始之前记录数据。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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