I'm trying to update some existing code that normally runs a Perl script which outputs a dynamically generated html page for messages, etc. Ultimately, my end result is to simply update a div
with the output of the Perl file rather than sending the user to a new page.
我试图更新一些现有的代码,这些代码通常运行一个Perl脚本,该脚本输出动态生成的html页面,用于消息等。最终,我的最终结果是使用Perl文件的输出更新一个div,而不是将用户发送到一个新的页面。
I've been down a couple roads trying to find the best way to do this. After failing to find a way to do this on the Perl side, I'm now looking at jQuery ajax()
.
我已经走了好几条路,试图找到做这件事的最好方法。在Perl方面没有找到实现这一点的方法之后,我现在研究jQuery ajax()。
Here is what I have so far and it's partially working:
这是我到目前为止所拥有的,部分有效的方法:
Perl:
Perl:
#!/usr/bin/perl
# =====================================================================
print "Content-type: text/html \n\n";
print "<p>Hello</p>";
HTML:
HTML:
<form id="myForm" action="#">
<input type="submit" value="click me" />
</form>
<div id="message"></div>
jQuery/JavaScript:
jQuery / JavaScript:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').submit(function() {
$.ajax({
type: 'POST',
url: '/cgi-bin/myPerl.cgi',
async: false,
success: function(data) {
$('#message').html(data);
}
});
});
});
</script>
1) When I click the button, the #message
div
only flashes the message for a second and then it goes blank. Why is that happening? This is my primary question.
1)当我点击按钮时,#message div只会闪现一秒钟的消息,然后就会变成空白。这是为什么发生?这是我的首要问题。
I also do not fully understand all the settings in .ajax()
despite my reading of the documentation:
我也不完全理解.ajax()中的所有设置,尽管我阅读了文档:
2) It only works at all if I use async: false
, otherwise with true
or leaving this setting out, I get a "failed to load resource" error. Can somebody explain.
2)如果我使用async,它只会起作用:false,否则为true或将此设置删除,我将会得到一个“未能加载资源”错误。有人能解释一下。
3) Is there a better way to do this? PHP? I just want to dynamically update a div
with the message coming from the Perl file, avoiding page refreshes or new pages.
有更好的办法吗?PHP吗?我只想用Perl文件中的消息动态更新一个div,避免刷新页面或新页面。
1 个解决方案
#1
4
Add return false
or e.preventDefault()
to the submit event.
向提交事件添加return false或e.preventDefault()。
$('#myForm').submit(function(e) {
e.preventDefault()
$.ajax({
type: 'POST',
url: '/cgi-bin/myPerl.cgi',
async: false,
success: function(data) {
$('#message').html(data);
}
});
// return false;
});
#1
4
Add return false
or e.preventDefault()
to the submit event.
向提交事件添加return false或e.preventDefault()。
$('#myForm').submit(function(e) {
e.preventDefault()
$.ajax({
type: 'POST',
url: '/cgi-bin/myPerl.cgi',
async: false,
success: function(data) {
$('#message').html(data);
}
});
// return false;
});