jQuery 如何使用ajax加载外部页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15375929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:56:21  来源:igfitidea点击:

How to load external page using ajax

jqueryajax

提问by cfz

i have a link button that supposed to link to another page. The content of that page should be displayed to the current page. I'm using the bootstrap framework, however the function I created doesn't seem to work.

我有一个链接按钮,应该链接到另一个页面。该页面的内容应该显示到当前页面。我正在使用引导程序框架,但是我创建的函数似乎不起作用。

here's my code;

这是我的代码;

<a href="" id="reslink">link1</a>

<div class="span8" id="maincont"></div>

javascript;

javascript;

$('#reslink').click(function(){
    $.ajax({
        type: "GET",
        url: "sample.html",
        data: { },
        success: function(data){
            $('#maincont').html(data);
        }
    });

});

回答by Dipesh Parmar

You have following ways.

你有以下方法。

First

第一的

use html as below,.

使用 html 如下,。

<a href="Javascript:void(0);" id="reslink">link1</a>

Javascript:void(0);work as return false from script.

Javascript:void(0);作为从脚本返回 false 的工作。

Second

第二

Do not change anything in html code but make below change in jQuerycode.

不要更改 html 代码中的任何内容,而是在jQuery代码中进行以下更改。

$('#reslink').click(function(e){
    e.preventDefault();
    $.ajax({
        type: "GET",
        url: "sample.html",
        data: { },
        success: function(data){
            $('#maincont').html(data);
        }
    });
});

e.preventDefault();prevent the default behaviorof the HTMLso you can execute your code.

e.preventDefault();阻止 的默认行为HTML以便您可以执行代码。

回答by SomeShinyObject

Maybe load()would be a better choice for you?

也许load()对你来说是更好的选择?

$("#reslink").click(function() {
    $("#maincont").load("sample.html");
});

Be mindful that loading content in this way could potentially break History and Favorites.

请注意,以这种方式加载内容可能会破坏历史记录和收藏夹。

回答by Pranav

body onload="abc()"in the loaded page should work when rendered from ajax.

body onload="abc()"从 ajax 渲染时,加载的页面应该可以工作。