Ajax调用语法

Ajax Call Syntax

本文关键字:语法 调用 Ajax      更新时间:2023-09-26

尝试做一个简单的ajax发布,由于某种原因,它没有发布我的数据!它成功地发布到文件(ajaxpost.php),但没有传递POST数据。。

            var myKeyVals = {caption: "test"};
                $.ajax({ //Process the form using $.ajax()
                    type        : 'POST', //Method type
                    url         : 'ajaxpost.php', //Your form processing file url
                    data        : myKeyVals, //Forms name
                    dataType    : 'json',
                    success     : function(data) {
                    if (!data.success) { //If fails
                        if (data.errors.name) { //Returned if any error from process.php
                            $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
                        }
                    } else {
                            $('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
                        }
                    }
                });

这是我的AjaxPost.php…

        <?php
        $text = $_GET['caption'];
        $file = 'people.txt';
        // Open the file to get existing content
        $current = file_get_contents($file);
        // Append a new person to the file
        $current = "LOG: " . $text . "'n";
        // Write the contents back to the file
        file_put_contents($file, $current, FILE_APPEND);
        ?>

在php文件中,您使用的是$_GET['caption'],但应该使用$_POST['caption'],因为这是一个post请求。

POST数据在PHP中使用$_POST而不是$_GET访问!

或者,如果您希望同时支持这两种HTTP方法,则可以使用$_REQUEST