【发布时间】:2010-11-22 16:41:20
【问题描述】:
我的 php 函数从 twitter 获取推文并将它们作为 json 编码字符串返回。 JS 脚本捕获该数据并使用 ajax 将其发布到 php 脚本。接收 php 脚本解码 json 并将其插入表中。但是没有数据进入mysql。错误控制台显示没有错误。这是我的代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<?php
function searchResults($q) {
$host = "http://search.twitter.com/search.atom?q=" . urlencode( $q ) . "&rpp=100";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//Raw xml
$result = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($result);
return json_encode($xml);
;
} //--------------- end of function
?>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<script>
$(document).ready(function()
{
var msg_top = new Array();
msg_top = "<"+"?php echo searchResults('windows');"+"?"+">";
var url = "msg2_mysql.php"
var request = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
request=new XMLHttpRequest();
}
else
{// code for IE6, IE5
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
alert('POST');
} else {
alert(request.status); //
}
}
}
request.send("msg_top=" + encodeURIComponent(msg_top).replace(/%20/g, '+'));
});
</script>
</body>
</html>
这是我用来向表中插入数据的脚本
<?php
$username = "******";
$password = "********";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL");
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
if($_POST['msg_top']!="")
{
$json = $_POST['msg_top'];
$msg = strtoupper(json_decode($json));
$query = "INSERT INTO msg2 (id,msg,msg_id,depth) VALUES ('','$msg','ID','3')";
mysql_query($query);
if(!mysql_query($query, $dbh))
{die('error:' .mysql_error());} echo'success';
}
else echo('no value!');
?>
【问题讨论】:
-
msg_top[] = ""; // 无论你用这条线做什么都是非常危险的。非常非常危险......就像......接管你的服务器并窃取你的生命危险。 -- 澄清一下,如果你稍后在你的服务器上运行它,有人可以使用 firebug 在你的服务器上运行任何代码。
-
那个 msg_top 是怎么回事?在从 JS 接收到它之后,你正在用 PHP 在你的服务器上评估它吗?但是你为什么要发送 PHP 标签呢?只需发送参数并将其添加到服务器上的代码中即可。不确定我是否理解那里发生的事情。
-
@Alex,对不起,我不明白你的第一个两个问题。发送php标签是什么意思?我想将结果从 php 传递给 js。 & js 实现了在页面加载时将这些结果插入 mysql 的 ajax。
-
你的代码有
<"+"?php echo searchResults('windows');"+"?"+">";。这是做什么的? DampeS8N 和我都认为这似乎表明存在严重的安全隐患。为什么要给自己发 PHP 代码? -
我从搜索中找到了这个方法来获取JS中的一个php变量。在这些 php 标记中,我运行 php 搜索函数,它以 json 格式返回推文,并传递给 js 变量。
标签: php javascript arrays simplexml