简体   繁体   English

WordPress在从URL获取参数的页面加载中使用Ajax

[英]Wordpress use ajax on page load from url get parameters

So i am building a search on website, and main search form is on home page where user can input information's like, interests, books, movies. 因此,我正在网站上进行搜索,主要搜索表单位于主页上,用户可以在其中输入信息,例如兴趣,书籍,电影。

And that form should submit to another page where search will be displayed. 并且该表单应提交到另一页,其中将显示搜索。 So it's similar like any other search, but on search page, i should keep parameters in url, so it's not going to be POST, it would be GET. 因此,它与任何其他搜索类似,但是在搜索页面上,我应该将参数保留在url中,因此它不会是POST,而是GET。

Home page is something like mywebsite.com 主页类似于mywebsite.com

And when form is submitted it's posted with GET parameters so user can keep search results in his url. 提交表单后,将使用GET参数发布表单,以便用户将搜索结果保留在其url中。 Submitted post should lead to something like. 提交的帖子应该导致类似的情况。

mywebsite.com/search?interests=sports&books=harry+potter&movies=moviename

And because it can take some time to search and load results i would like to load the page and than do an ajax post to search function and populate search results once ajax responds. 而且由于搜索和加载结果可能需要一些时间,所以我想加载页面,而不是ajax发布搜索功能并在ajax响应后填充搜索结果。

I've built in past some ajax content loading and post and load data with ajax, but all that while keeping on same page, i never built when you submit content from one page to another in wordpress. 我已经建立了过去的一些ajax内容加载以及使用ajax发布和加载数据的方法,但是所有这些都保持在同一页面上,而当您在wordpress中将内容从一页提交到另一页时,我从未构建过。

Any suggestions how can i do that and make ajax grab the content ? 有什么建议我该怎么做,并使ajax抓取内容?

I found the answer, and it's actually quite easy, instead triggering ajax with function, for example function with button click. 我找到了答案,实际上很简单,而是使用功能(例如,单击按钮的功能)来触发ajax。

Just trigger ajax on page load, and don't enqueue script anywhere else except on that page, this would help a bit. 只需在页面加载时触发ajax即可,除了在该页面上之外,不要将脚本排入其他任何地方,这会有所帮助。

if ( is_page_template('template-search.php') ) {
    wp_enqueue_script('ajax_search');
}

This will ensure script is loaded only on that template page, and as for script it self, just load ajax on page ready: 这将确保仅在该模板页面上加载脚本,对于脚本本身,只需在准备就绪的页面上加载ajax即可:

jQuery(document).ready(function($) {
jQuery.ajax({
    dataType: 'json',
    url: search_flight.ajaxurl,
    data: {
        action: 'search_flight',
    },
    beforeSend: function() {

    },
    success: function(data) {
        console.log(data);
    },
    error: function() {
    }
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM