javascript 如何提交表单并在当前页面的 Div 内加载目标页面?

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

How to Submit a form and load target page inside a Div on the Current page?

javascriptjavascript-events

提问by BastiaanWW

I am new to Javascript and didn't arrive to find a working script that does the following:

我是 Javascript 的新手,并没有找到执行以下操作的工作脚本:

I have a hidden form in javascript that should be submitted on an onclick event. The fields in the form are used in the target php file to create output. The target php file should be loaded inside a div on the current page without reloading the whole page.

我在 javascript 中有一个隐藏的表单,应该在 onclick 事件上提交。表单中的字段在目标 php 文件中用于创建输出。目标 php 文件应加载到当前页面的 div 内,而无需重新加载整个页面。

The problem is that I cannot get the target php file to load inside the div on the current page, but the target php page is simply loaded showing the results that I want to have inside the div.

问题是我无法将目标 php 文件加载到当前页面的 div 内,但是目标 php 页面只是加载,显示了我想要在 div 内的结果。

Any help would be very appreciated!

任何帮助将不胜感激!

Update #1

更新 #1

I did a youtube tutorial on jquery ajax request where the result is shown in a div on the same page. I double checked the code many times and it looks the same as in the tutorial. In the tutorial the code is working but for me it isn't. Below are all the files I'm using and the code.

我做了一个关于 jquery ajax 请求的 youtube 教程,其中结果显示在同一页面的 div 中。我多次检查代码,它看起来与教程中的一样。在教程中,代码正在运行,但对我来说却不是。下面是我正在使用的所有文件和代码。

ajax.html:

ajax.html:

<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

//
$(document).ready(function(){

$("#button").click(function(){
var sendu = $("#username").val();
var sendp = $("#password").val();

$.ajax({
type="POST",
url: "ajax.php",
data: "username="+sendu+"&password="+sendp,
dataType: "json", 
success: function(msg,string,jqXHR){
$("#result").html(msg.name+"<br />"+msg.password);
}
});
});
});


</script>
</head>

<body>
Name:<input type="text" id="username" name="username" /><br />
Password:<input type="password" id="password" name="password" /><p>
<input type="button" id="button" value="submit" />
<p><div id="result"></div>
</body>
</html>

jquery.js from this url: http://code.jquery.com/jquery-1.6.2.min.js

jquery.js 来自这个网址:http: //code.jquery.com/jquery-1.6.2.min.js

ajax.php:

ajax.php:

<?

$name = $_REQUEST['username'];
$password = $_REQUEST['password'];

$list = array('name'=>$name, 'password'=>$password);

$c = json_encode($list);

echo $c;
?>

I'm using the WAMP server as my localhost, could it have anything to do with a setting?

我使用 WAMP 服务器作为我的本地主机,它与设置有什么关系吗?

回答by Nisk

Since you provided no code, I'll have to guess, either:

由于您没有提供任何代码,我将不得不猜测:

1) You have the AJAX code to load the php response into a division but the page still refreshes, in which case - when the form is submitted you need to prevent the default event triggering, do this with:

1) 您有 AJAX 代码将 php 响应加载到分区中,但页面仍会刷新,在这种情况下 - 提交表单时,您需要防止触发默认事件,请执行以下操作:

event.preventDefault();

Stick that as the first thing inside the function that get's executed inside the onClick(). It should all work now. Incidentally, you probably want onSubmit() instead, in case someone hits 'Enter' instead of clicking the 'submit' button (although I'm not sure if it's part of the standard javascript/DOM). Check out a javascript library called JQuery, it makes javascript a breeze.

将其作为在 onClick() 中执行的函数中的第一件事。现在应该都可以了。顺便说一句,您可能想要 onSubmit() ,以防有人点击“Enter”而不是点击“提交”按钮(尽管我不确定它是否是标准 javascript/DOM 的一部分)。查看一个名为 JQuery 的 javascript 库,它使 javascript 变得轻而易举。

2) You actually want AJAX, in which case go to jquery.com, download their javascript library and go through some tutorials on ajax requests. The basics are something like:

2) 您实际上需要 AJAX,在这种情况下,请访问 jquery.com,下载他们的 javascript 库并阅读有关 ajax 请求的一些教程。基本的东西是这样的:

$("#id_of_your_form").submit(function(event){
    event.preventDefault();
    $.post( url_of_php_file, $("#id_of_your_form").serialize(), function(data){
        $("#id_of_your_div").html(data);
    });
});

This code is basic, but should work, provided you remember to include the library file in your .html file.

这段代码是基本的,但应该可以工作,前提是您记得在 .html 文件中包含库文件。

#UPDATED

#更新

Is there any particular reason you're using the JSON object? I just haven't used it before myself, so my input here might be limited. Try this:

您使用 JSON 对象有什么特殊原因吗?我只是自己之前没有使用过它,所以我在这里的输入可能有限。试试这个:

ajax.html

ajax.html

<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

//
$(document).ready(function(){

    $("#button").click(function(event){ //don't forget to pass the event as an argument

        //need this, or your page will follow the url defined in the form
        event.preventDefault();

        var sendu = $("#username").val();
        var sendp = $("#password").val();

        $.ajax({
        type: "POST",
        url: "ajax.php",
        data: "username="+sendu+"&password="+sendp, /*shouldn't the method be GET then?*/
        dataType: "json", 
        success: function(msg){
            $("#result").html(msg.name+'<br />'+msg.password);
        }
        });
    });
});


</script>
</head>

<body>
    <form action="miss.php" method="post">
        Name:<input type="text" id="username" name="username" /><br />
        Password:<input type="password" id="password" name="password" /><p>
        <input type="submit" id="button" />
    </form>
<p><div id="result"></div>
</body>
</html>

ajax.php

ajax.php

<?

$name = $_POST['username']; //use $_POST array instead
$password = $_POST['password'];

$list = array('name'=>$name, 'password'=>$password);

$c = json_encode($list);

echo $c;
?>

(Note: I haven't checked the php code as such, since as I said, I'm not too familiar with JSON objects) If you don't specifically need the json object, you could try using standard text/xml for simplicity. Also, consider using $.postinstead of $.ajax, it should make things easier.

(注意:我没有检查过 php 代码,因为正如我所说,我对 JSON 对象不太熟悉)如果您不是特别需要 json 对象,为了简单起见,您可以尝试使用标准 text/xml . 另外,考虑使用$.post而不是$.ajax,它应该会让事情变得更容易。

Also, don't forget to use the formtags around your input or your html won't be valid(citation needed) and finally, if you're working with html in your javascript it might be a good idea to use single quotes instead of double quotes to indicate your strings. Hope that helped.

另外,不要忘记在您的输入周围使用表单标签,否则您的 html 将无效(需要引用),最后,如果您在 javascript 中使用 html,那么使用单引号可能是个好主意双引号来表示你的字符串。希望有所帮助。

#UPDATE 2

#更新 2

Okay, since you don't need JSON for basic stuff(leave JSON for later), use text/xml instead. Also, have a look at the comments. This should all work, provided WAMP is running and both files are in the same folder. Here's the code:

好的,由于基本内容不需要 JSON(将 JSON 留待以后使用),请改用 text/xml。另外,看看评论。如果 WAMP 正在运行并且两个文件都在同一个文件夹中,这一切都应该有效。这是代码:

ajax.html

ajax.html

<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

//
$(document).ready(function(){

    $("#login_form").submit(function(event){    //don't forget to pass the event as an argument

        //need this, or your page will follow the url defined in the form
        event.preventDefault();

        var sendu = $("#username").val();
        var sendp = $("#password").val();

        $.post("ajax.php", {'username' : sendu, 'password' : sendp}, function(data){
            $("#result").html(data); //data is everything you 'echo' on php side
        });

    });
});


</script>
</head>

<body>
    <form action="miss.php" method="post" id="login_form">
        Name:<input type="text" id="username" name="username" /><br />
        Password:<input type="password" id="password" name="password" /><p>
        <input type="submit" id="button" />
    </form>
<p><div id="result"></div>
</body>
</html>

ajax.php

ajax.php

    <?php
//you used shorthand <? as the php tag, it's probably why your code didn't work
//I would discourage using the shorthand, it's silly

$name = $_POST['username']; //use $_POST array instead
$password = $_POST['password'];

echo $name.'<br />'.$password;

?>

If this doesn't work...check if you have skype running, for some reason WAMP will not work with skype on at the same time, it's weird.

如果这不起作用...检查您是否正在运行 Skype,由于某种原因 WAMP 不能同时与 Skype 一起使用,这很奇怪。

回答by Kumar

You can use Ajax. The run of the mill Ajax will let you refresh parts of the page w/out reloading the page, which in your case is submit the form and load the target on the current page. I will suggest you to start with jQuery.

您可以使用 Ajax。磨坊 Ajax 的运行将使您无需重新加载页面即可刷新页面的某些部分,在您的情况下,这是提交表单并在当前页面上加载目标。我建议你从 jQuery 开始。

回答by Johnny Craig

the problem is the form is still submitting, when i do what your trying to do, i do it slightly different. try this

问题是表格仍在提交,当我做你想做的事情时,我做的有点不同。试试这个

<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function gO(frM){
    $.ajax({
        type:"POST",
        url: "ajax.php",
        data: frM.serialize(),
        dataType: "json", 
        success: function(msg,string,jqXHR){
            $("#result").html(msg.name+"<br />"+msg.password);
        }
    });
}

</script>
</head>

<body>
    <form action="" onsubmit="javascript:gO(this);return false;">
       Name:<input type="text" id="username" name="username" /><br />  
       Password:<input type="password" id="password" name="password" /><p>
       <input type="button" id="button" value="submit" />
     </form>
<p><div id="result"></div>
</body>
</html>