我正在尝试让一个jQuery脚本在幕后使用php运行。它基本上会用jQuery(works)获取div的内容,然后用ajax(works)调用一个脚本,但我需要调用php的ajax脚本将vars发送到php,这样我就可以保存连接。
这是代码:
<script>
$( document ).ready(function() {
$( ".tweets" ).click(function() {
var htmlString = $( this ).html();
tweetUpdate(htmlString);
});
});
</script>
<script>
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
</script>
和我的保存推文代码.php
<?
// SUPPOSED TO receive html conents called htmlString taken from a div
// and then I will write this code to a file with php and save it.
echo $_POST[htmlString];
?>
你必须为参数命名,以便 PHP 可以检索它。将调用$.ajax
更改为执行操作:
data: { htmlString: htmlString },
然后在 PHP 中,您可以引用 $_POST['htmlString']
来获取参数。
更正你的功能。
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: "htmlString="+htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
然后在 saveTweets.php 页面上写下行,您将在该页面上获得价值。
echo '<pre>';print_r($_REQUEST );echo '</pre>';
使用 json 更适合发送数据:
data_htlm=[];
data_html.push({"htmlString": htmlString});
$.ajax(
{
type: "POST",
dataType: "json",
url: "saveTweets.php",
data: JSON.stringify(data_html),
success: function(html)
{
console.log(html);
}
});
现在使用 PHP,您可以这样做:
echo $_POST['htmlString'];
您可以使用
$.post
方法发布到 PHP 页面,然后在回调函数中从该页面检索结果。