如何在不刷新页面的情况下发送表单数据 [英] How to send form data without page refresh?

查看:143
本文介绍了如何在不刷新页面的情况下发送表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用提交按钮在ajax中发送数据而没有任何页面刷新。
但页面刷新。

I have sending my data in ajax using submit button without any page refresh. But the page refreshed.

请检查我的代码并告诉我这个问题。

Please check my code and let me know the problem.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$("#idForm").submit(function() { alert("hi");

    var url = "ajax.php";
    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(),
           success: function(data) {
               alert(data);
           }
         });

    return false;
});
</script>
<form id="idForm" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

ajax.php

echo "Hello";


推荐答案

js已经阻止表单提交



问题已经中的代码阻止表格通过此行提交:

The js already prevents the form submitting

The code in the question already prevents the form from submitting by this line:

return false;

这意味着:问题中的JavaScript代码根本没有运行。

which means: The JavaScript code in the question isn't running at all.

这里的问题是当这行代码运行时:

The problem here is that when this line of code runs:

$("#idForm")...

该元素尚未在dom中。因此,提交处理程序没有附加到任何东西 - 当表单提交它时,它只是一个标准的HTTP post请求。

that element isn't in the dom yet. As such the submit handler isn't attached to anything - when the form submits it's just a standard HTTP post request.

要解决问题中的问题 - 做一个以下

To just fix the problem in the question - do one of the following

如果脚本在元素出现后运行在源代码中 - 形式存在:

If the script runs after the element appears in the source code - the form does exist:

<form id="idForm">...
<script>
    $("#idForm")...
</script>



将jquery代码放入文档就绪处理程序



如果js处于就绪处理程序中:

Put jquery code in a document ready handler

If the js is in a ready handler:

<script>
    $(function() {
        $("#idForm")...
    });
</script>
<form id="idForm">...

它没有脚本标记的位置,因为dom在运行时已经完成加载。

It doesn't matter where the script tag is as the dom has already finished loading when it runs.

如果系统地将javascript放在页面末尾:

If javascript is systematically put allat the end of the page:

<body>
    <form id="idForm">...
    ...
    <script src="//ajax.googleapis.c...
    <script>
        $("#idForm")...
    </script>
</body>

这将是建立最佳实践,避免此类问题,不需要在任何js代码中使用现成的处理程序(因为html源代码在脚本中总是已经在dom中以这种方式解析)并且让页面感觉加载速度更快。

That would be following established best practices, avoid such problems, don't need to use ready-handlers in any js code (as the html source is always already in the dom when scripts are parsed that way) and have pages that are perceived to load faster.

这篇关于如何在不刷新页面的情况下发送表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆