简体   繁体   English

页面加载后的Ajax调用

[英]Ajax call after page load

I am trying to build a search page where the user inputs text into a search box and the page is generated based on the search. 我试图建立一个搜索页面,用户在其中输入文本到搜索框中,然后根据搜索结果生成页面。 I am having timing issues because the blank search page is loading after the JS tries to edit the values on the page. 我遇到时间问题,因为在JS尝试编辑页面上的值后,正在加载空白搜索页面。

$.ajax({
    type: 'GET',
    url: '/index.php/content/generate_search',
    data: {
        search: input.val()
    },
    beforeSend: function() {
        window.location.href = '/index.php/content/search';
    },
    success: function() {
        $('.hero h1').text(input.val());
    }
});

To check that the DOM is completely loaded, many steps have to be done taking all the browsers into consideration. 为了检查DOM是否已完全加载,必须考虑所有浏览器完成许多步骤。 (I cannot find the implementation in the jQuery source, but I will come back with a link). (我无法在jQuery源代码中找到实现,但是我将返回一个链接)。

The easiest and probably best way of doing it, since you're already using jQuery is by: 因为您已经在使用jQuery,所以最简单,可能也是最好的方法是:

$( function() {
    // your code here
} );

which is a shorthand for 这是的简写

$( document ).ready( function() {
    // your code here
} );

EDIT 编辑

Ok, so as I promised, I came back with the implementation of document.ready . 好的,正如我所答应的,我返回了document.ready的实现。 You can find it here, on GitHub. 您可以在GitHub上找到它。 Here is a permanent link to the current version of the file. 是指向文件当前版本的永久链接。

Try this: 尝试这个:

$(document).ready(function(){
 //Your  code
});

onload is used for executing code on pageload onload用于在pageload上执行代码

window.onload = function() {
  // your code
};

This code: 这段代码:

 beforeSend: function() { window.location.href = "/index.php/content/search"; }, 

… is causing the browser to leave the page and load a new one before it sends the Ajax request. …导致浏览器在发送Ajax请求之前离开页面并加载新页面

Consequently, the Ajax request gets cancelled. 因此,Ajax请求被取消。 If it didn't, then there would be no JavaScript waiting to receive the response. 如果没有,那么就不会有JavaScript等待接收响应。

If you want to visit /index.php/content/search and then initiate an Ajax request, then the JavaScript to initiate the Ajax request has to be on /index.php/content/search . 如果要访问/index.php/content/search然后启动Ajax请求,则启动Ajax请求的JavaScript必须在/index.php/content/search A page you've just left can't run JavaScript on the next page. 您刚离开的页面无法在下一页上运行JavaScript。

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

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