2010-08-04 111 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>