jQuery Ajax:发送存储在变量中的数据

时间:2022-08-08 16:59:32

I need to send the JSON data in a jQuery's ajax call like this:

我需要以jQuery ajax调用的方式发送JSON数据:

$.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    data: '{"assessmentId":1,"pageId":1,"currentPage":2}',
    async: false,
    success: function(data) {
    // TO DO
    }
});

This is working fine but the data I am sending needs to be stored in a variable like this:

这很好,但我发送的数据需要存储在这样的变量中:

var jsonSendingData = '{"assessmentId":1,"pageId":1,"currentPage":2}';

Once I keep it in a variable jsonSendingData and pass in ajax call, it gives me error.

一旦我将它保存在变量jsonSendingData中并传入ajax调用,它就会给我带来错误。

I also tried to stringify the json data like this:

我还尝试像这样对json数据进行stringify:

var jsonSendingData = JSON.stringify([{"assessmentId":1,"pageId":1,"currentPage":2}]);

It does not work. What am I doing wrong here?

它不工作。我在这里做错了什么?

2 个解决方案

#1


2  

You don't need to send the data as a string, jQuery will do that for you. Try this

您不需要将数据作为字符串发送,jQuery将为您完成这一任务。试试这个

var myData = {
  assessmentId: 1,
  pageId: 1,
  currentPage: 2
};

$.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    data: myData, //Notice the change here
    async: false,
    success: function(data) {
      // TO DO
    }
});

PS: There is a very similar answer here. Please check that.

这里有一个非常相似的答案。请检查。

#2


1  

You don't need the quotes when storing in variable.

在变量中存储时不需要引号。

var jsonSendingData = {
    assessmentId:1,
    pageId:1,
    currentPage:2
};

jQuery.ajax({
       url:url,
       type:'POST',
       data:jsonSendingData
  }).done(function(data){
   console.log(data);
 });

Otherwise you have to specify it in the request headers

否则,您必须在请求头中指定它

var datastring = JSON.stringify(jsonSendingData);

data: datastring,
contentType: "application/json",

#1


2  

You don't need to send the data as a string, jQuery will do that for you. Try this

您不需要将数据作为字符串发送,jQuery将为您完成这一任务。试试这个

var myData = {
  assessmentId: 1,
  pageId: 1,
  currentPage: 2
};

$.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    data: myData, //Notice the change here
    async: false,
    success: function(data) {
      // TO DO
    }
});

PS: There is a very similar answer here. Please check that.

这里有一个非常相似的答案。请检查。

#2


1  

You don't need the quotes when storing in variable.

在变量中存储时不需要引号。

var jsonSendingData = {
    assessmentId:1,
    pageId:1,
    currentPage:2
};

jQuery.ajax({
       url:url,
       type:'POST',
       data:jsonSendingData
  }).done(function(data){
   console.log(data);
 });

Otherwise you have to specify it in the request headers

否则,您必须在请求头中指定它

var datastring = JSON.stringify(jsonSendingData);

data: datastring,
contentType: "application/json",