2013-05-27 39 views
0

此代碼假設接受用戶值,然後給出相應的警報框但它不起作用。我可以知道這段代碼有什麼問題嗎?我做了很多谷歌搜索(很多指向這個網站),但我似乎無法找到解決方案?請提前幫助和感謝。使用jQuery發佈多個變量


的index.html

<html> 
<head> 
<title>the title</title> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.0.min.js"></script> 

<script type="text/javascript"> 

function check() { 
     var one = $('#first').val(); 
     var two = $('#second').val(); 
     var three = $('#third').val(); 
     var four = $('#fourth').val(); 

    $.post("result.php", { 
    first: one, 
    second: two, 
    third: three, 
    fourth: four 
},function(data) 
     { 

     if (data=="yay") //for no input 
     { alert("yay"); 
     } 
     else 
     { 
     alert("nay"); 
     } 

     } 


     } 

</script> 

</head> 
<body> 

     <form name="form"> 
    <input type="text" id="first"> 
    <input type="text" id="second"> 
    <input type="text" id="third"> 
    <input type="text" id="fourth"> 
    <input type="button" value="get" onclick="check();"> 
    </form> 


</body> 
</html> 

result.php

<?php 

    $one = $_POST["first"]; 
     $two = $_POST["second"]; 
     $three =$_POST["third"]; 
     $four = $_POST["fourth"]; 
     if($one > 5)   
     { 

     echo "yay"; 
     } 
    elseif($two > 10)  { 

     echo "yay"; } 

      elseif($three > 15)   
      { 

     echo "yay"; 
      } 

      elseif($four > 20)   
      { 

     echo "yay"; 
      } 

      else{ 
       echo "nay"; 
      } 

?> 
+2

我想補充'達taType' json並回顯一個'json_encode'數組,結果 –

+0

使用.serialize()作爲表單man – Sam

+0

它不會輸出任何內容嗎?在使用AJAX的結果中的if語句之前,請對數據進行警報:alert(data);檢查其輸出。 –

回答

1

的JSON的dataType

///<script .... 
    $.post("result.php", { 
    first: one, 
    second: two, 
    third: three, 
    fourth: four 
},function(data){ 
    if (data.response=="yay") { alert("yay"); } 
    else { alert("nay"); } 
},"json"); 

//</script> 

<?php 

    $one = $_POST["first"]; 
    $two = $_POST["second"]; 
    $three =$_POST["third"]; 
    $four = $_POST["fourth"]; 

    if($one > 5)   
     { 

     $response = "yay"; 
     } 
    elseif($two > 10)  { 

     $response = "yay"; } 

      elseif($three > 15)   
      { 

     $response = "yay"; 
      } 

      elseif($four > 20)   
      { 

     $response = "yay"; 
      } 

      else{ 
       $response = "nay"; 
      } 

      echo json_encode(array("response" => $response)); 

?> 
+0

我添加'$ lol = array('response'=> $ response); 回聲json_encode($ lol);'它工作。我感謝您的幫助。無論如何,我迷惑爲什麼一些教程,我看到他們不包括JSON。 json和serialize是一樣的嗎?只有當你發佈的變量超過一個時才使用它? 我再次感謝您的幫助。 – sg552

+0

Serialize的工作方式與此完全相同,只是爲您節省了一些打字費用。 –