简体   繁体   English

错误:AJAX响应内的AJAX调用

[英]error: AJAX call within AJAX response

I am working with a file to interact with an API. 我正在使用文件与API进行交互。 First the API sends some HTML and Javascript to create a search form, then the API can process the query of that search form. 首先,API发送一些HTML和Javascript来创建搜索表单,然后API可以处理该搜索表单的查询。

I am having some problems with my second request, which is called within the success function of the first request (this seems to be the problem!). 我的第二个请求有一些问题,在第一个请求的成功函数中被调用(这似乎是问题!)。 Here's the code I'm working with. 这是我正在使用的代码。

$.ajax({
  type: "POST",
  url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
  crossDomain: true,
  data: JSON.stringify({
    "stage": "load",
    "fields": ["first_name", "last_name", "graduation_year"]
  }),

  success: function(response) {
    response = JSON.parse(response);
    $(response.html).prependTo("#content");
    $(response.scripts).appendTo("body");
  },

  complete: function() {
    //get field inputs
    var fieldInput = {
      "first_name_query": "",
      "last_name_query": "",
      "graduation_year_query": ""
    };

    $('form').find('input[type=search]').each(function(index, value) {
      var variableName = value.name;
      var fieldId = "#" + value.name;

      $(fieldId).keyup(function() {
          variableName = $(this).val();
          fieldInput[value.name + "_query"] = variableName
          console.log(value.name + ":" + fieldInput[value.name + "_query"]);
        })
        .keyup();
    });

    $('#search_form').submit(function(event) {
      event.preventDefault();
      $.ajax({
        type: "POST",
        url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
        data: JSON.stringify({
          "stage": "search",
          "fields": ["first_name", "last_name", "graduation_year"],
          "query": {
            "first_name": fieldInput["first_name_query"]
          }
        }),

        success: function(response) {
          response = JSON.parse(response);
          console.log(response);
        }
      });

    })

  }
});

When trying to parse the response, I get unexpected token: o. 尝试解析响应时,出现意外的令牌:o。 If I run this code outside of the first ajax request like this: 如果我在第一个ajax请求之外运行此代码,如下所示:

$.ajax({
  type: "POST",
  url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
  data: JSON.stringify({
    "stage": "search",
    "fields": ["first_name", "last_name", "graduation_year"],
    "query": {
      "first_name": "Bob"
    }
  }),


  success: function(response) {
    response = JSON.parse(response);
    console.log(response);
  }
});  

I don't have any problem and the code executes normally. 我没有任何问题,代码正常执行。 So the problem seems to be running one Ajax call inside another's success response, but I don't know why? 因此,问题似乎出在另一个Ajax调用的另一个成功响应中,但是我不知道为什么? I can probably do things another way instead, but wanted to see if anyone had some insight into why this doesn't work. 我可能可以用另一种方式来做事,但是想看看是否有人对为什么这行不通有所了解。

The error you are getting suggests that you are trying to parse an object with JSON.parse since 您收到的错误表明您尝试使用JSON.parse解析对象,因为

var x = {}
console.log(x.toString()) //> [object Object]
JSON.parse(x)
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
//    at JSON.parse (<anonymous>)
//    at <anonymous>:3:6

Are you sure that response is a string in the second case 您确定在第二种情况下响应是字符串吗

Instead of explicitly converting the JSON allow jquery to parse it for you with dataType: 'json' 无需显式转换JSON,而是允许jquery使用dataType: 'json'为您解析它

$.ajax({
  type: "POST",
  url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
  data: JSON.stringify({
    "stage":"search",
    "fields":["first_name","last_name","graduation_year"],
    "query":{"first_name": fieldInput["first_name_query"] }
  }),
  dataType: 'json'
)}

So the problem ended up being pretty strange. 因此,问题最终变得非常奇怪。 I'm developing an API for Nationbuilder platform (maybe my first mistake). 我正在为Nationbuilder平台开发API(也许是我的第一个错误)。 For unknown reasons, Nationbuilder was appending a authenticity token to any request made, which my LAMBDA based API couldn't parse. 出于未知原因,Nationbuilder会将真实性令牌附加到发出的任何请求中,而我的基于LAMBDA的API无法解析该请求。 Just in case anyone else is in the same very tiny boat as I was, I ended up using GET requests instead of POST requests and Nationbuilder stopped appending the authenticity token. 万一其他人和我一样,我最终使用GET请求而不是POST请求,并且Nationbuilder停止添加真实性令牌。

Also, if anyone is using Lambda, I ended up switching to Digital Ocean hosted Express JS and am much happier. 另外,如果有人在使用Lambda,我最终会改用Digital Ocean托管的Express JS,并且会更快乐。

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

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