使用ajax调用php函数

Call the php function using ajax

本文关键字:函数 php 调用 ajax 使用      更新时间:2023-09-26

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

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

我基本上想把编辑器中编写的内容存储到一个文件中(最好是富文本格式)。我使用了一个脚本(下面给出)将内容存储在一个字符串中。(我通过引用HTMLdiv文本来保存和显示)

<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,但不知道如何使用?感谢您的帮助。

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

$.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参数的限制相对较小。