我有一个下拉表单,其中包含用户可以选择的四个选项列表。选择后选择 并点击"在公共聊天中做广告"按钮选项值(1,2,3,4)需要传递给advertise.php?advertise = 1(2,3或4) 没有页面刷新。点击广告在公共聊天后,我想要一条消息,说“"消息发送到聊天!"用户可以单击“确定”。
我的问题:
代码不会在Firefox或Internet Explorer上执行(我在Debian Linux和Windows PC上试过 - 所有这些都有相同的结果)。在Chrome \ Opera上完美运行。
<!DOCTYPE html> <html> <body> <form id="myform" action="" method="post"> <select name="Type"> <option value="1">(1 on 1)</option> <option value="2">(2 on 2)</option> <option value="3">(3 on 3)</option> <option value="4">(4 on 4)</option> </select> <input type="submit" value="Advertise in Public Chat"> </form> <div id="message"><h2>This will change when the request is sent</h2></div> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" ></script> <script type="text/javascript"> $(document).ready(function(event) { $('form').on('submit', function(){ event.preventDefault(); var myVal = $('select[name="Type"]').val(); $.ajax({ type: "GET", url: "advertise.php", data: { advertise: myVal } }).done(function( response ) { // response is equal to what advertise.php will echo/print $('#message h2').html("Message sent to Chat!"); }); }); }); </script> </body> </html>
答案 0 :(得分:1)
如果您 - 提交表单,页面将会刷新。您必须停止或阻止表单的提交事件的默认操作。以下是使用jquery的示例:
$('#myForm').on('submit', function(e){
e.preventDefault();
// your ajax function
});
答案 1 :(得分:1)
而不是使用
<input type="submit" value="Advertise in Public Chat">
您可以使用
<input type="button" id="submit-btn" value="Advertise in Public Chat">
对于ajax你可以这样做:
$("#submit-btn").click(function(){
$.ajax({
type: "POST",
url: "advertise.php",
data: dataString,
success: function() {
$('#message').html("<h2>Message sent to Chat!</h2>")
}
});
});
});
答案 2 :(得分:0)
就像你可以在advertise.php中访问$ _GET [&#39; advertise&#39;]
<强>更新强>
我忘了第一次把花括号放在数据声明中,现在它会起作用
<script type="text/javascript"> $('#myForm').on('submit', function(e){ e.preventDefault(); var myVal = $('select[name="Type"]').val(); $.ajax({ type: "GET", url: "advertise.php", data: { advertise: myVal }, success: function() { $('#message').html("<h2>Message sent to Chat!</h2>"); } }); }); </script>
更新2 我刚刚在本地进行了测试,并假设advertise.php与此文件处于同一级别。
<!DOCTYPE html> <html> <body> <form id="myform" action="" method="post"> <select name="Type"> <option value="1">(1 on 1)</option> <option value="2">(2 on 2)</option> <option value="3">(3 on 3)</option> <option value="4">(4 on 4)</option> </select> <input type="submit" value="Advertise in Public Chat"> </form> <div id="message"><h2>This will change when the request is sent</h2></div> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" ></script> <script type="text/javascript"> $(document).ready(function() { $('form').on('submit', function(event){ event.preventDefault(); var myVal = $('select[name="Type"]').val(); $.ajax({ type: "GET", url: "advertise.php", data: { advertise: myVal } }).done(function( response ) { // response is equal to what advertise.php will echo/print $('#message h2').html("Message sent to Chat!"); }); }); }); </script> </body> </html>