【问题标题】:prevent form from refreshing on submit - Ajax Call Angular JS防止表单在提交时刷新 - Ajax Call Angular JS
【发布时间】:2018-03-04 07:54:06
【问题描述】:

我正在制作一个搜索表单。这种形式有两个值The job title 和Location。并根据这些关键字从网络上抓取数据。提交表单时,表单会刷新。因此,出于这个原因,我将event.preventDefault() 放在表单提交上。但问题是在 URL 中没有出现表单值。

我想要的也是获取 URL,并阻止页面刷新。

表单通过GET 方法发送值。 action 属性是index.php,即页面本身。

到目前为止我做了什么:

<form method="GET" action="index.php" id="search-form">
			<input type="text" placeholder="Job Title" class="job-search-inp job-title-inp" autocomplete="off" name="job_title" required>
			<input type="text" placeholder="Job Place" class="job-search-inp job-type-inp" autocomplete="off" name="job_loc" required>
			<button  type="submit" id="submit_btn"> <i class="fa fa-search"></i> </button>
</form>

同一 index.php 页面中的 Ajax 请求:

$("body").on("submit", "#search-form", function(e) {

  var _e = e.target;

  console.log($(_e).serialize());
  $("#submit_btn i").hide();
  $("#submit_btn").html('<img src="ajax-loader.gif">');

  $http({
    method: "GET",
    url: "crawler3.php",
    data: $(_e).serialize() + "&start=0&crawl=true",
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }).then(function(res) {
    $("#submit_btn").html('<i class="fa fa-search"></i>');
    console.log(res.data);
  })
})

这就是我希望 URL 的外观:http://localhost.com/Fiverr/Job%20Crawler/index.php?job_title=web&amp;job_loc=pakistan。 由于结果将显示在同一 index.php 页面上,我不希望刷新页面。

【问题讨论】:

  • 您包含标签javascript,jquery,html 和ajax,而您的索引文件是index.php。这可能是一个错误吗?
  • @FDavidov 这个问题与所有人有关,这就是为什么

标签: javascript jquery html ajax


【解决方案1】:

通过添加简单的两行代码解决了问题:

window.history.pushState('index.php',
  'title',
  window.location.pathname + '?' + $(_e).serialize()
);

【讨论】:

    【解决方案2】:

    在提交时添加 return false。

    $("body").on("submit", "#search-form", function(e) {
    ...
    ...
    
     $http({
       method: "GET",
       url: "crawler3.php",
       data: $(_e).serialize() + "&start=0&crawl=true",
       headers: {
       'Content-Type': 'application/x-www-form-urlencoded'
      }
     }).then(function(res) {
       $("#submit_btn").html('<i class="fa fa-search"></i>');
       console.log(res.data);
     })
    
     return false;
    
    })
    

    【讨论】:

      猜你喜欢
      • 2015-03-05
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      相关资源
      最近更新 更多