1

我正在尝试使用 php 在幕后运行 jQuery 脚本。它基本上会使用 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>

和我的 saveTweets.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];

?>
4

4 回答 4

4

您必须为参数命名,以便 PHP 可以检索它。改变$.ajax调用做:

data: { htmlString: htmlString },

然后在你的PHP中,你可以引用$_POST['htmlString']来获取参数。

于 2013-11-03T10:10:36.993 回答
1

纠正你的功能。

  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>';
于 2013-11-03T10:12:21.613 回答
1

使用 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'];
于 2019-05-29T09:16:59.507 回答
0

您可以使用该$.post方法发布到 PHP 页面,然后在回调函数中从该页面检索结果。

于 2013-11-03T12:17:23.740 回答