jQuery - 它为什么不工作?

时间:2014-10-22 13:20:47

标签: jquery ajax

这是index.php的代码,显示带有“Connect Me”按钮的表单。我想当用户按下该按钮时,它将变为“正在连接...”,并将POST数据发送到startTransaction.php脚本(位于同一目录中),并在POST数据发送后显示一条消息,或者如果发生任何错误,将显示错误消息。但是当我按下“连接我”时,它只是重新加载页面。 index.php的内容是:

< !doctypehtml > < htmllang = "en" > < head > < metacharset = "UTF-8" / > < title > Freecalls, nosignuprequired! < / title > < linkrel = "stylesheet"href = "css/style.css" />
< scriptsrc = "js/jquery.min.js" > </script>
<script src="js/jquery.ui.shake.js"></script>
<script>
$(document).ready(function() {

$('#call').click(function()
{
var caller=$("#caller").val();
var receiver=$("#receiver").val();
var dataString = 'caller='+caller+'&receiver='+receiver;
if($.trim(caller).length>0 && $.trim(receiver).length>0)
{


$.ajax({
        type: "POST",
        url: "startTransaction.php",
        data: dataString,
        cache: false,
        beforeSend: function(){ $("#call").val('Connecting...');},
        success: function(data){
        if(data)
        {
         $('#box').shake();
 $("#call").val('Connect')
 $("#error").html("<span style='color:#cc0000'>All set! </span> We'll call you in 5 minutes to connect you. ");

        }
          else
        {
         $('#box').shake();
 $("#call").val('Connect')
 $("#error").html("<span style='color:#cc0000'>Error:</span> An error occured.");
        }
        }
        });

}
return false;
});


});
</script>
</head>

<body>
<div id="main">
<h1>Start making free calls now!</h1>

<div id="box">
<form action="" method="post">
<label>What's your number?</label> 
<input type="text" name="caller" class="input" autocomplete="off" id="caller"/>
<label>And your friend's? </label>
<input type="text" name="receiver" class="input" autocomplete="off" id="receiver" />
<br/>
<input type="submit" class="button button-primary" value="Connect Me!" id="connect"/> 
<span class='msg'></span> 

<div id="error">

</div>
// html closing tags here

请告诉我我错在哪里:)

3 个答案:

答案 0 :(得分:3)

按钮的ID为connect,而不是call

$('#connect').click(function(){
   //Click on the button
});

答案 1 :(得分:2)

包含jquery的脚本标记似乎不正确

< scriptsrc = "js/jquery.min.js" > </script>

应该是(缺少脚本和src之间的空格)

<script src = "js/jquery.min.js" > </script>

答案 2 :(得分:1)

你需要这个:

// this is the id of the form
$("#idForm").submit(function() {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
               //Or your own code to execute when response is successful
           }
         });

    return false; // avoid to execute the actual submit of the form.
});

来自:https://stackoverflow.com/a/6960586/1275832