Javascript 功能仅在有警报时才有效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21416345/
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
Javascript function only works if there's an alert
提问by Sebastian
This code executes post.php
:
此代码执行post.php
:
function SubmitForm() {
var input = $("#input").val();
var user = "anon";
$.post("post.php", {input: input, user: user}, function(data) {});
alert("hello");
}
But if I remove a line, this doesn't:
但是,如果我删除一行,则不会:
function SubmitForm() {
var input = $("#input").val();
var user = "anon";
$.post("post.php", {input: input, user: user}, function(data) {});
}
Seems irrational, but why is this happening?
似乎不合理,但为什么会发生这种情况?
The PHP which the JS should call inserts some values into the database:
JS 应该调用的 PHP 将一些值插入到数据库中:
<?php
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
// Create connection
$con = mysqli_connect($dbhost, $dbuser, $dbpass);
// Check connection
if (!$con) {
die("Database connection failed: " . mysqli_error());
}
// Select database
$db_select = mysqli_select_db($con, $dbname);
// Check selection
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$message = $_POST["input"];
$user = $_POST["user"];
echo $message;
echo $user;
$query = "INSERT INTO posts (user, message) VALUES ('$user', '$message')";
mysqli_query($con, $query);
?>
回答by Rocket Hazmat
Your problem is that this function is being called in an onsubmit
/onclick
event handler. AJAX is asynchronous, meaning it runs in the background. When you call $.post
, the code continues on and the callback is called at some point in the future.
您的问题是在onsubmit
/onclick
事件处理程序中调用了此函数。AJAX 是异步的,这意味着它在后台运行。当您调用 时$.post
,代码会继续运行,并在将来的某个时间点调用回调。
What is happening is that the form is being submitted, so the page is being redirected. This is happening before the AJAX call finishes. The alert
pauses the browser, so it gives the AJAX call a chance to finish.
发生的事情是表单正在提交,因此页面正在被重定向。这是在 AJAX 调用完成之前发生的。该alert
暂停的浏览器,所以它给人的AJAX调用机会完成。
You need to block browser from performing the "default" action.
您需要阻止浏览器执行“默认”操作。
<input type="submit" class="button" id="button_post" value="POST" onclick="SubmitForm(); return false;">
P.S. I suggest that you bind event handlers in JavaScript versus inline handlers.
PS 我建议你在 JavaScript 中绑定事件处理程序而不是内联处理程序。
<input type="submit" class="button" id="button_post" value="POST">
<script>
$(function(){
$('#button_post').click(function(e){
e.preventDefault();
SubmitForm();
});
});
</script>
回答by Fenton
It probably does work (or the POST
is failing in both cases).
它可能确实有效(或者POST
在两种情况下都失败了)。
To see whether it really works, your alert should be inside of the callback - as that is the code that will run if the request succeeds.
要查看它是否真的有效,您的警报应该在回调内 - 因为这是如果请求成功将运行的代码。
function SubmitForm() {
var input = $("#input").val();
var user = "anon";
$.post("post.php", {input: input, user: user}, function(data) {
alert(data);
});
}
It is always worth firing up your browser's developer tools to see the network request and check that it works.
总是值得启动浏览器的开发人员工具来查看网络请求并检查它是否有效。
回答by Wayne
This is almost certainly related to the fact that $.post
is executed asynchronouslyand you're not properly accounting for that. The alert
is pausing execution, which is buying you some time for the post
to finish, so that anything that needs its result later might actually have access to that result. Removing the alert
removes this pause and breaks anything that was relying on this side-effect. (In other words, something that needs the result of post
is executing before the post
has finished.)
这几乎肯定与异步$.post
执行的事实有关,而您没有正确考虑这一点。该是暂停执行,这是给你买一些时间来完成,从而使任何以后需要其结果实际上可能有机会获得这一结果。删除删除此暂停并破坏依赖此副作用的任何内容。(换句话说,需要结果的东西在完成之前正在执行。)alert
post
alert
post
post
You should perform any action that relies on the results of the $.post
inside the callback that is passed to it:
您应该执行任何依赖于$.post
传递给它的回调内部结果的操作:
$.post("post.php", {input: input, user: user}, function(data) {
// do anything that relies on this post here
});
回答by John S
You say in a comment that you have:
你在评论中说你有:
<input type="submit" class="button" id="button_post" value="POST" onclick="SubmitForm();">
In that case, the form will get posted by the normal means. When you have an alert, the ajax call is able to succeed, but without the alert, the normal form submission probably prevents the ajax call.
在这种情况下,表单将通过正常方式发布。当您有警报时,ajax 调用能够成功,但没有警报,正常的表单提交可能会阻止 ajax 调用。
You should either change the button so it is not a "submit" button:
您应该更改按钮,使其不是“提交”按钮:
<input type="button" ...
Or prevent the normal form submission by returning false in the "onclick":
或者通过在“onclick”中返回 false 来阻止正常的表单提交:
<input ... onclick="SubmitForm(); return false;">
回答by user254153
The easiest way would be run your jquery after the DOM has finished loaded. I also faced similar problem. Just add the function to be called inside:
最简单的方法是在 DOM 加载完成后运行你的 jquery。我也遇到了类似的问题。只需在里面添加要调用的函数:
$(window).load(function(){
// your function here.
});
回答by OuzoPower
As Rocket Hazmat mentioned, many puzzling issues when your code is awaiting results from Ajax calls come from the asynchronous mode. The problem comes from the fact that the code goes on before the Ajax query completed.
正如 Rocket Hazmat 所提到的,当您的代码等待 Ajax 调用的结果时,许多令人费解的问题来自异步模式。问题来自于代码在 Ajax 查询完成之前继续运行的事实。
Using the synchronous mode forces waiting the answer from the Ajax call.
When using jQuery, jQuery.ajax()
supports setting the async
option to false: async: false
(instead of the default: true
).
使用同步模式强制等待来自 Ajax 调用的应答。使用 jQuery 时,jQuery.ajax()
支持将async
选项设置为 false:(async: false
而不是默认值:)true
。
Some libraries have methods which forgot the to implement the possibility of performing synchronous calls. As a "silent" alternative to adding calls like alert(" ");
, a possible workaround in such case is adding a setTimeout() that triggers something silent, like writing something to the console. It is not "clean" code but can be useful.
More details here: https://stackoverflow.com/a/49835054
一些库的方法忘记了实现执行同步调用的可能性。作为添加类似调用的“静默”替代alert(" ");
方法,在这种情况下可能的解决方法是添加一个 setTimeout() 来触发一些静默的东西,比如向控制台写入一些东西。它不是“干净”的代码,但很有用。更多细节在这里:https: //stackoverflow.com/a/49835054