【发布时间】:2015-11-06 16:41:36
【问题描述】:
我已经在这个问题上花费了 10 多个小时,并且基本上在整个互联网上搜索了一个解决方案。这是一个简单的 jQuery ajax POST 方法,我之前成功使用过几次。过去我也遇到过这个问题,但以某种方式解决了它。我传递的数据似乎没问题,在 chrome 的网络控制台中,它甚至显示了一个带有假定数据的成功帖子。但是,使用 .load 获取该数据始终返回 null。在下面的代码中,我使用了一个阻止默认提交的表单来阻止刷新。一个按钮触发sellBook(),提示一个表单,提交后触发post()。
JS
function sellBook(i) {
$('#results').html('');
title = books[i].title;
author = books[i].author;
ISBN = books[i].ISBN;
publisher = books[i].publisher;
image = books[i].image;
year = books[i].year;
$('#results').html('Listing for ' + books[i].title + ' by ' + books[i].author + '<br><br><form method="post" action="https://localhost/textbookexchange/db2.php" id="sellIt">Edition #: <input type="text" id="edition" name="edition"/><br><br>Price: $<input type="text" id="price" name="price"><br><br>Condition: <input type="text" id="condition" name="condition"><br><br><input type="submit" value="Submit"><br><br></form>');
getInfo();
$('#sellIt').submit(function () {
post();
return false;
});
}
function post() {
price = document.getElementsByName('price')[0].value;
edition = document.getElementsByName('edition')[0].value;
condition = document.getElementsByName('condition')[0].value;
var formData = {
A: title,
B: author,
C: ISBN,
D: publisher,
E: image,
F: year,
G: soldby,
H: fblink,
I: price,
J: edition,
K: condition
};
var url = 'db2.php/'
jQuery.ajax({
type: 'POST',
url: url,
data: formData,
success: function (data) {
alert(data);
$('#results').load("db2.php/");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
},
});
}
当我收到数据警报时,我总是返回成功,而不是错误。
在我的 apache 错误日志中,我得到了这个:
[2015 年 8 月 13 日星期四 11:24:15.666854] [:error] [pid 4255] [client 127.0.0.1:50476] PHP 注意:未定义索引:/var/www/html/textbookexchange/db2.php 中的 A第2行,referer:https://localhost/textbookexchange/
db2.php(the php file POSTED to)
<?php
echo $_POST['A'];
?>
我尝试将其解析为 JSON,重置 contentType,设置 dataType,将 crossdomain 设置为 true,async 设置为 false,使用 jsonp,使用 $.post,使用更少的数据(只有一个变量),以及其他一些东西..
【问题讨论】:
-
查看连接上的“标题”选项卡,您应该会看到实际发送到 PHP 的内容。 javascript 范围可能意味着“标题”实际上并未在 post() 中定义;
-
漂亮的屏幕截图:)
-
谢谢,我需要提供更多有关问题的背景信息,包括我的屏幕和键盘的视觉效果。
-
我推荐使用 jqXHR 对象的 Promise 方法:
done(),fail(),always(),then()。在jQuery "弃用通知:jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调自 jQuery 1.8 起已弃用。" -
@kchow 仅供参考:你需要试试那个神奇的按钮,它真的很棒:}(见键盘按钮:imgur.com/nsfc2T5)
标签: javascript php jquery ajax post