Javascript 如何在不重新加载整个页面的情况下重新加载 div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7175038/
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-24 01:11:40  来源:igfitidea点击:

How to reload a div without reloading the entire page?

javascriptjqueryajaxhtmlreload

提问by Gabriele

I suppose what I am asking is really easy for most of you. I want to reload a div without reloading the entire page. What's the best way to do it?

我想我问的对你们大多数人来说真的很容易。我想重新加载一个 div 而不重新加载整个页面。最好的方法是什么?

<div class="black_text" id="cp_in_content_div">
<?php
$id = $_GET["id"];
$result = mysql_query("SELECT * FROM Setting WHERE ID = $id");
$row = mysql_fetch_array($result);
switch ($_GET["action"])
{
    case "delete":
    if (!unlink("$_SERVER[DOCUMENT_ROOT]setting/$row[Filename]"))
    {
        echo "Error.";
        header("Refresh: 2.5; URL=delete_setting.php?id=$id");
        exit();
    }
    if (!mysql_query("DELETE FROM Setting WHERE ID = $id"))
    {
        echo "Error.";
        header("Refresh: 2.5; URL=delete_setting.php?id=$id");
        exit();
    }
    else
    {
        echo "Ok!";
        header("Refresh: 1.25; URL=index.php");
    }
    break;
    default:
    echo "form";
}
?>
</div>

I need those header("Refresh:...") to only reload the div instead of the page.

我需要那些 header("Refresh:...") 只重新加载 div 而不是页面。

回答by Explosion Pills

jQuery.load()is probably the easiest way to load data asynchronously using a selector, but you can also use any of the jquery ajax methods (get, post, getJSON, ajax, etc.)

jQuery.load()可能是使用选择器异步加载数据的最简单方法,但您也可以使用任何 jquery ajax 方法(get、post、getJSON、ajax 等)

Note that load allows you to use a selector to specify what piece of the loaded script you want to load, as in

请注意,load 允许您使用选择器来指定要加载的已加载脚本的哪一部分,如

$("#mydiv").load(location.href + " #mydiv");

Note that this technically does load the whole page and jquery removes everything but what you have selected, but that's all done internally.

请注意,这在技术上确实会加载整个页面,而 jquery 会删除除您选择的内容之外的所有内容,但这都是在内部完成的。

回答by genesis

$("#div_element").load('script.php');

demo: http://sandbox.phpcode.eu/g/2ecbe/3

演示:http: //sandbox.phpcode.eu/g/2ecbe/3

whole code:

整个代码:

<div id="submit">ajax</div> 
<div id="div_element"></div> 
<script> 
$('#submit').click(function(event){ 
   $("#div_element").load('script.php?html=some_arguments');  

}); 
</script> 

回答by praveena

Use this.

用这个。

$('#mydiv').load(document.URL +  ' #mydiv');

Note, include a space before the hastag.

请注意,在 hastag 之前包含一个空格。

回答by Ambala Chandrashekar

write a button tag and on click function

编写一个按钮标签和点击功能

var x = document.getElementById('codeRefer').innerHTML;
  document.getElementById('codeRefer').innerHTML = x;

write this all in onclick function

把这一切写在 onclick 函数中