【问题标题】:How to utilize a value from the response of one .AJAX function in another as a parameter to insert into the POST request如何利用另一个 .AJAX 函数响应中的值作为参数插入到 POST 请求中
【发布时间】:2019-10-01 21:44:12
【问题描述】:

我正在尝试使用从一个 ajax 函数中的响应接收到的值作为 html 文件中另一个 ajax 函数调用的参数。 如果这是非常基本的,我很抱歉,但我对此很陌生。

我已经尝试像在 HTML 正文中一样调用该值以及许多其他尝试。

1 - 这是初始调用(工作):

$.ajax({
          "url":api_base+"/endpoint_01",
          "type":"GET",
          "contentType":"application/json",
          "success":function(data){
            var data = data[0];
            $('#dash_value').html(data.value);
          }
        });

2 - 这是我在 html 中访问它的方式 (:

<div class="highlighted-text" id="dash_value"></div>

3 - 我不知道如何在文件后面使用它:

function function_02(){
          $.ajax({
            "url":api_base+"endpoint_02?value=" + dash_value,
            "type":"POST",
            "beforeSend":function(){
              $('#button_01').prop('disabled', true);
            },
            "dataType":"text",
            "success":function(data){
              swal(data, {
                icon : "success",
                buttons: false,
                timer: 3000
              });
            },
            "complete":function(){
              $('#button_01').prop('disabled', false);
            }
          });
        }

POST 应该像这样发送:

   https://endpoint02?value=dash_value

但我得到了除此之外的一切。请帮忙。

【问题讨论】:

    标签: html ajax http-post


    【解决方案1】:

    尝试在 Ajax 方法范围之外声明一个变量,以便方法外部的代码稍后可以访问它,然后将变量分配给 ajax 范围内的返回数据:

    var outerScopeData = "";
    
    $.ajax({
      "url":api_base+"/endpoint_01",
      "type":"GET",
      "contentType":"application/json",
      "success":function(data){
        var data = data[0];
    
        // add this here:
        outerScopeData = data.value;
    
        $('#dash_value').html(data.value);
      }
    });
    

    【讨论】:

      【解决方案2】:

      在进行第二次 ajax 调用之前,您需要定义 dash_value

      
      
      function function_02(){
               const dash_value = $("dash_value").data()
                $.ajax({
                  "url":api_base+"endpoint_02?value=" + dash_value,
                  "type":"POST",
                  "beforeSend":function(){
                    $('#button_01').prop('disabled', true);
                  },
                  "dataType":"text",
                  "success":function(data){
                    swal(data, {
                      icon : "success",
                      buttons: false,
                      timer: 3000
                    });
                  },
                  "complete":function(){
                    $('#button_01').prop('disabled', false);
                  }
                });
              }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-27
        • 1970-01-01
        • 2016-06-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多