2010-08-04 109 views
1

我試圖使用POST傳遞變量從try.htm到chat.php

爲try.htm的代碼是:

<head> 
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script type = "text/javascript"> 
    function yo() { 
     var text = $("#msg").val(); 
     $.post("chat.php",msg:text); 
    } 
</script> 
</head> 
<body> 

<input type="text" id="msg" onkeyup="yo()"> 
<div id="display">Change</div>    
</body> 

爲chat.php的代碼是:

<?php 
$msg=$_POST['msg']; 
mysql_connect("localhost","root"); 
mysql_select_db("user"); 
mysql_query("INSERT INTO user (name,pwd,status) VALUES ('$msg','work','0')") or die(mysql_error()); 
?> 

問題是'msg'變量似乎沒有傳遞到chat.php! 有什麼問題?

+0

其實你應該得到語法/解析錯誤。 – 2010-08-04 13:03:26

回答

2

將其更改爲:

$.post("chat.php", { msg:text }); 

jQuery的預期數據,作爲一個對象來傳遞和{ ... }基本上將創建一個匿名對象對我們來說。 msg:text - 沒有花括號 - 不幸的是沒有太多的工作,並會在運行時拋出錯誤。

因此,將兩者放在一起:{ msg:text }創建一個匿名對象,其屬性爲msg,其值爲text變量。

0

你就錯了,請使用正確的JSON對象:

$.post("chat.php", { msg:text }); 
+0

這不是一個JSON對象。這是一個普通的舊字面JavaScript對象;) – 2010-08-04 13:04:53

+0

好吧,猜你是對的:) – 2010-08-04 14:08:31

0

你忘了花括號一輪$。員額

$.post("chat.php",{msg:text}); 
1

參數的數據參數作爲數組傳遞:

<head> 
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script type = "text/javascript"> 
    function yo() { 
     var text = $("#msg").val(); 
     $.post("chat.php", {msg:text}); 
    } 
</script> 
</head> 
<body> 

<input type="text" id="msg" onkeyup="yo()"> 
<div id="display">Change</div>    
</body>