javascript - 防止表单在提交时刷新 - Ajax Call Angular JS

标签 javascript jquery html ajax

我正在处理一个搜索表单。此表单采用两个值 The job titleLocation。并根据这些关键字从网络上抓取数据。提交表单时,表单会刷新。因此,出于这个原因,我将 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);
  })
})

This is how I want the URL to look : http://localhost.com/Fiverr/Job%20Crawler/index.php?job_title=web&job_loc=pakistan. As the results of will be displayed on the same index.php page, I do not want the page to be refreshed.

最佳答案

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

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

关于javascript - 防止表单在提交时刷新 - Ajax Call Angular JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49093220/

相关文章:

Javascript/jQuery : get height when max-height is set to 0

javascript - videojs 播放器 + google IMA 广告 - 如何订阅事件

javascript - 由 jQuery 触发时,不会触发使用 addEventListener() 添加的事件

javascript - IE 9.0 中的卸载问题

php - 创建一个 php/mysql 表单嵌入到许多不同的网站

javascript - 创建可以在不同应用程序中显示路线/行程的链接

javascript - JQuery Animate 的问题

php - 如何阻止 Tidy2 添加额外的 HTML 标签? ( Notepad++ )

html - Firefox 的表单输入字段呈现问题

javascript - 一开始如何不启用切换类?