首页 > 解决方案 > Ajax 响应不会打印到目标元素中?

问题描述

我一直在使用 postcodes.io 来构建一个简单的表单来搜索用户的邮政编码数据。我可以很好地查询 postcodes.io 并获得响应,您可以在控制台日志中看到该响应。但无论出于何种原因,在我的情况下,我似乎无法将响应打印到目标元素中$('.ajaxResponse').html(response);

我很难过这一点,任何帮助将不胜感激。

$(document).ready(function() {
  $('#ajaxSubmit').click(function() {
    $.ajax({
      type: "get",
      url: 'https://api.postcodes.io/postcodes/' + $('#userPostCode').val(),
      dataType: 'json',
      success: function(response) {
        console.log(response); // Returns data;
        console.log($('.ajaxResponse')); // Is descoverable
        $('.ajaxResponse').html(response); // Not working ?
      },
      error: function(xhr, ajaxOptions, thrownError) {
        var msg = '';
        if (xhr.status === 0) {
          msg = 'Not connect.\n Verify Network.';
        } else if (xhr.status == 404) {
          msg = 'Requested page not found. [404]';
        } else if (xhr.status == 500) {
          msg = 'Internal Server Error [500].';
        } else if (thrownError === 'parsererror') {
          msg = 'Requested JSON parse failed.';
        } else if (thrownError === 'timeout') {
          msg = 'Time out error.';
        } else if (thrownError === 'abort') {
          msg = 'Ajax request aborted.';
        } else {
          msg = 'Uncaught Error.\n' + xhr.responseText;
        }
      }
    });
  });
  $('#ajaxSubmit').submit(function(e) {
    e.preventDefault();
  });
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <div class="jumbotron">
    <h1>Search Postcodes.io</h1>

    <form method="get" action="">
      <div class="form-row align-items-center mb-3">
        <div class="col-auto">
          <label class="sr-only" for="userPostCode">Postcode</label>
          <input type="text" name="postcode" class="form-control form-control-lg mb-2" id="userPostCode" placeholder="AL1 2BQ" required>
        </div>
        <div class="col-auto">
          <button type="button" id="ajaxSubmit" class="btn btn-lg btn-primary mb-2">Submit</button>
        </div>
      </div>
    </form>
    
    <p>The response:</p>
    <div class="ajaxResponse"></div>

</div>

标签: phpajax

解决方案


如果它是一个 JSON 对象,也许您需要对其进行字符串化。你能试试:$('.ajaxResponse').text(JSON.stringify(response));


推荐阅读