【发布时间】: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