【问题标题】:Sending POST data to PHP script - jQuery, AJAX & PHP将 POST 数据发送到 PHP 脚本 - jQuery、AJAX 和 PHP
【发布时间】:2017-04-23 03:43:24
【问题描述】:

我似乎很难将 POST 数据发送到我的 PHP 脚本。

我的 AJAX 将数据(博客文章的 ID)发送到我的 PHP 脚本,然后从数据库中找到包含匹配 ID 的行。

然后,该脚本将博客文章的标题和文章内容以数组的形式发回,AJAX 将其拾取并插入到 DOM 中的表单中。

我可以成功:

  • 插入示例数据(例如,如果我只是将字符串存储到要传递回 AJAX 的数组中,它会成功地将这些字符串插入到表单中);和
  • 在指定静态 ID 时从数据库中插入正确的数据(例如,如果我切换出 $_POST['editpostid'] 并改为指定整数 5,则查询成功找到 ID = 5 和 AJAX 的行将此数据插入到表单中)。

因此,在我看来,问题在于 ID 永远不会到达 PHP 脚本,或者我的脚本无法看到 JSON 对象中的 ID。

请看看我的代码,让我知道你的想法。我对这一切都很陌生,因此非常感谢您的反馈 - 如果它解决了问题。

Javascript/jQuery:

// When edit button is clicked
$('li.edit').click(function() {

    // Get class (postid inserted with PHP) of edit button, excluding edit class
    var oldpostid = $(this).attr('class').split(' ')[1];

    alert(oldpostid); // Returns the correct postid, for example 5

    var jsonObj = { 'postid': oldpostid };

    alert(jsonObj); // Returns 'object Object'

    // Send postid to PHP script
    $.ajax({
        type: 'POST',
        url: '../scripts/fetchpost.php',
        dataType: 'json',
        data: { 'editpostid': jsonObj },
        success: function() {

            // Fetch post data back from script
            $.getJSON('../scripts/fetchpost.php', function(data) {

                alert(data.title); // Returns null
                alert(data.content); // Returns null

                // All of the below code works if the PHP script returns sample text,
                // or if an ID is specified in the PHP script itself

                var title = data.title;
                var content = data.content;

                // Insert data into editor
                $('#titlehead').text(title);
                $('#edittitle').val(title);
                var editor = 'editpost-content';
                tinymce.get(editor).setContent(content);
            });
        },
        error: function( e ) {
        console.log(e.message);
    }
    });
});

PHP:

<?php

// Specifies connection details
include('../scripts/config.php');

// Fetch data from AJAX
$postid = $_POST['editpostid']; // Where I think the problem lies. Returns null.
// Again, this works if I switch out $_POST with an integer, such as 5

// Find rows in database that match postid
$postedit_qry = mysqli_query( $dbconnect, "SELECT * FROM posts WHERE postid='$postid'" );

// Store results in an associative array
$row = mysqli_fetch_assoc( $postedit_qry );

// Split array into variables
$title = $row['title'];
$content = $row['content'];

// Organise data into an array for json
$postedit = array(
    'title' => $title,
    'content' => $content
);

// Return array as json object for ajax to pick up
echo json_encode( $postedit );

// Close connection
mysqli_close( $dbconnect );

?>

更新 - 解决方案:

固定 jQuery/Javascript:

// Snip

// Get class (postid inserted with PHP) of edit button, excluding edit class
    var oldpostid = $(this).attr('class').split(' ')[1];

    // Send postid to PHP script
    $.ajax({
        type: 'POST',
        url: '../scripts/fetchpost.php',
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        data: { "editpostid": oldpostid },
        success: function(data) {

            var title = data.title;
            var content = data.content;

// Snip

PHP 脚本保持不变。

非常感谢您的帮助! 小猪先生

【问题讨论】:

  • 感谢您的所有回答!我结合了 Farzad 和 Spencer 的建议来修复它,包括我自己使用 PHP 文档进行的研究。我已经更新了我的原始问题以包含解决方案。

标签: javascript php jquery mysql ajax


【解决方案1】:

我认为你错过了索引'postid',需要替换它

$postid = $_POST['editpostid'];

这一行:

$postid = $_POST['editpostid']['postid'];

或者代替发送

data: { 'editpostid': jsonObj },

发送这个

data: { 'editpostid': oldpostid },

【讨论】:

  • 感谢您的回复法扎德。我的代码现在可以工作了,这是由于 Spencer 和你自己帮助我找到了一些错误。我发现你的第二个建议对我有用,我完全放弃了这个数组。感谢您的帮助! :)
  • @MrPupper 非常乐意提供帮助:)
【解决方案2】:

查看您的代码,您似乎得到了 null,因为您两次请求 fetchpost.php 脚本。一次是通过$.ajax(...); 联系脚本,一次是在您致电$.getJSON(...); 时。但是,当您通过$.getJSON(...); 联系时,您不是POSTing 数据,并且您的脚本似乎没有正确定义的方式来处理GET 请求,因此脚本不知道如何做出反应并且它返回空信息。

我会将 JavaScript/jQuery 更改为以下内容:

// When edit button is clicked
$('li.edit').click(function() {

    // Get class (postid inserted with PHP) of edit button, excluding edit class
    var oldpostid = $(this).attr('class').split(' ')[1];

    alert(oldpostid); // Returns the correct postid, for example 5

    var jsonObj = { 'postid': oldpostid };

    alert(jsonObj); // Returns 'object Object'

    // Send postid to PHP script
    $.ajax({
        type: 'POST',
        url: '../scripts/fetchpost.php',
        dataType: 'json',
        data: {'editpostid': jsonObj },
        success: function(sData) {
            var data = JSON.parse(sData);
            alert(data.title); // Returns null
            alert(data.content); // Returns null

            // All of the below code works if the PHP script returns sample text,
            // or if an ID is specified in the PHP script itself

            var title = data.title;
            var content = data.content;

            // Insert data into editor
            $('#titlehead').text(title);
            $('#edittitle').val(title);
            var editor = 'editpost-content';
            tinymce.get(editor).setContent(content);
        },
        error: function( e ) {
            console.log(e.message);
        }
    });
});

此外,PHP 将期望 application/x-www-form-urlencoded 值能够与 $_POST[...] 交互。因此,如果你想给它提供 JSON,那么在你的 PHP 中,你需要实现一个解决方案,例如:$postedData = json_decode(file_get_contents('php://input')); (在this answer 中查看更多信息;关于json_decode 的更多信息,请参见the official PHP documentation for json_decode.)


注意:虽然超出了您的问题范围,并且您可能已经知道这一点,但我发现重要的是要指出您的 MySQL 不安全并且容易受到 SQL 注入的影响,因为只是盲目信任postId 未被篡改。在初始化 $dbconnect 并连接到数据库之后,但在将 $postid 放入 SQL 查询字符串之前,您需要通过说 $postid = $dbconnect-&gt;real_escape_string($postid); 来清理它。

【讨论】:

  • 非常感谢 Spencer,我的代码现在可以运行了!代码本身在几个地方被破坏了,Farzad 和你自己都帮助修复了这些地方。我还发现删除包含 JSON.parse() 的行完全可以让我的代码正常工作。关于您关于 SQL 安全性的说明,我完全了解并感谢您的提醒。此代码用于大学作业项目,不会作为生产代码发布,因此我们不希望涵盖这些安全方面。但是,我已经注意到您对未来项目的评论,感谢您给我的反馈! :)
  • @MrPupper,啊,我不确定是否需要 JSON.parse,或者 jQuery 库是否会自动将其转换为对象,因为指定了 dataType。而且我认为您可能知道 SQLi 漏洞,但是当我看到它时,我总是试图指出它,因此有人不会发布可能危及其用户/客户的易受攻击的代码:P 无论如何,很高兴能提供帮助。祝你学业顺利。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
  • 2012-05-17
相关资源
最近更新 更多