1

我想GET用ajax 发出一个API 请求。我有一个 jquery 函数从第一个输入字段中获取一个 api 键值,然后在输入字段 #2 上显示一个连接结果url + api key。我需要对第二个输入字段中显示的值发出获取请求。我怎样才能完成这个获取请求?目标服务器设置为允许跨域脚本站点

<script>
$(document).ready(function () {
    $(document).ready(function() {

  /** get the inputs we might need */
  var $result = $('#result');
  var $input = $('#input');

  $result.data('url', $result.val());
  var timer;

  /** function to submit data to the server and
      update the result input on success */
  function submitForm( input, newValue) {
    $.ajax({
      type: "POST",
      url: "/concatenate/index.php",
      data: {input:input},
      success: function (data) {
        $result.val(newValue);
      }
    });
  };

  /** on key up, fill #result with the url + input */
  $input.bind('keyup', function() {
    var $this = $(this);
    var inp = $this.val();
    var url = $result.data('url');
    var newValue = url + inp + '/';

    if(timer) { clearTimeout(timer); }
    timer = setTimeout(function(){
      submitForm(inp, newValue) ;
    }, 40);
    return false;
  });

});
});
</script>

</head>
<body>

<h1>Enter a word:</h1>

<form action="index.php" method="post">
API Key: <input type="text" id="input" name="input"></br>
Concatenated Url + API: <input type="text" style="width:200px;" id="result" name="result" value="http//www.example.com/"></br>
</form>
4

1 回答 1

2

我确信可能有很多其他方法可以做到这一点,但我脑海中浮现的第一个想法是在submitForm. 原因是,当达到超时并准备好进行 ajax 调用时,您需要input在该确切时刻获取该字段中的任何内容,以确保您拥有最“最新”的值(越多越好)。所以也许是这样的:

// Note: I've ditched the parameters because they are no longer needed
// We're getting the values that the parameters contained in this function
function submitForm() {
  var inp = $("#input").val();
  var url = $("#result").data('url');
  var concatenatedUrl = url + inp + '/';

  $.ajax({
    type: "GET",
    url: concatenatedUrl,
    data: {input:input},
    success: function (data) {
      $result.val(newValue);
    }
  });
}

希望有帮助。请让我知道我是否误解了这个问题。

于 2013-11-10T03:09:26.990 回答