在用户提交表单后显示数据(从API调用检索),而不刷新页面

Displaying the data (retrieved from an API call) after user submit the form without refreshing the page

本文关键字:检索 刷新 调用 API 表单 提交 用户 显示 数据      更新时间:2023-10-06

我正在创建一个表单,该表单将在提交时从用户获得搜索查询请求,并在进行API调用后显示结果。我希望在不使用AJAX刷新页面的情况下显示结果。我正在使用PHP连接到API。

这是我到目前为止所做的,但我无法显示结果。不管API连接是否成功,如果不刷新页面,我甚至无法在同一页面中显示表单的条目,所以我不确定我是否做得正确。我错过了什么?我还需要考虑什么才能做到这一点?有人能给我指引正确的方向吗?

$(document).ready(function() {
      $('#search-form').on('submit', (function(e) {
          e.preventDefault();
          $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            dataType: 'json',
            data: $(this).serialize(),
            success: function(data) {
              console.log(data);
              $('#results').html(data);
            }
          });
        });
      });
<form action='result.php' method='post' id='search-form'>
  <input type='search' name='search'>
  <input type='submit' value='submit'>
</form>
<div id='results'>Result comes here..</div>

//result.php

if(isset($_POST['search'])) {
    $query = urlencode( $_POST[ "search"]);
    $request = 'http://some.api/?query=' . $query;
    $response=file_get_contents($request); 
    $result=json_decode($response); 
    echo ($result);
} else {
    echo ("No search query has received");
}

.serialize()不序列化提交按钮。提交按钮只有在按下/触发其所在表单上的提交操作时才会在请求中发送,.serialize()对此一无所知
您只需要手动添加该信息,或者根本不检查它。

...
data: $(this).serialize()='&submit=ajax',
...

if(!empty($_POST['search'])) {
...

我建议在这种情况下,您只需创建一个隐藏字段,其值如下:

<input type="hidden" name="search" value="submitted" />

这将在提交时出现。