使用ajax调用php函数

时间:2014-10-23 04:05:51

标签: javascript php jquery html ajax

我在html页面中嵌入了一个编辑器

<div id="editor">
Problem Statement goes here&hellip;
</div>

我基本上希望将编辑器中编写的内容存储到文件中(最好是富文本格式)。我使用了一个脚本(如下所示)将内容存储在一个字符串中。(我通过引用HTML div text to save and display使用)

<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> 
     var StoreEditorContent;  //declare a variable to save Content

      document.getElementById('save').addEventListener("click", SaveText);  // adding event listner for onclick for Saving text

    function SaveText(){

       StoreEditorContent = document.getElementById('editor').innerHTML; // Save the Content into 
       document.getElementById('editor').innerHTML = ""; // to blank the editor Content
       window.onload = function(){

                $.ajax({
                    url: "submit_request.php",
                    type: "GET",
                    success: function writeMsg(StoreEditorContent){
                       //Not sure if this part is right.
                    }
                });   
        }
    }

    </script>

这当然是将内容存储在字符串StoreEditorContent中。我现在想把这个字符串传递给一个php函数,它将这个(StoreEditorContent)写入一个文件。包含写入函数的php文件如下所示

<?php

function writeMsg($msg){
    $file = "myfile.txt";
    file_put_contents($file, $msg);
}
?>

我知道我需要在这里使用ajax,但无法弄清楚如何?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

您需要向data:提供$.ajax()选项:

$.ajax({
    url: "submit_request.php",
    type: "POST",
    data: { content: StoreEditorContent },
    success: function (response) {
        // Do something with the response sent from PHP
    }
});

然后您的PHP可以:

writeMsg($_POST['content']);

您应该使用POST而不是GET来处理大型请求,因为GET参数的限制相对较小。