我写了一个通用的ajax函数。而不是多次写入。因此,我只是将帖子数据和URL发送到我的常用功能。直到这里一切都很好,我也得到了回应。但是我在阅读该回复时遇到了麻烦。
function _ajax_post(someData,URL)
{
var ajaxCall = $.ajax({
type: 'POST',
data: someData,
dataType: 'json',
url: URL
});
ajaxCall.done(function(data) {
console.log("A good programmer looks both ways before crossing a one-way street :) ");
});
ajaxCall.fail(function(data) {
console.log(" Design is choosing how you will fail.");
});
ajaxCall.always(function() {
console.log("Truth can only be found in one place: the code.");
});
return ajaxCall;
}
我在这里打来电话
$('#btnOutput').on('click', function () {
var str = $("#out").text();
var r = _ajax_post({"data":str},url+"roles/vu_menus/tets");
console.log(r);
});
在我的console.log()中,我得到的响应是
{readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort: ƒ (a)
always: ƒ ()
complete: ƒ ()
done: ƒ ()
error: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ (a)
overrideMimeType: ƒ (a)
pipe: ƒ ()
progress: ƒ ()
promise: ƒ (a)
readyState: 4
responseJSON: {data: "[{"text":"Home","href":"http://home.com","icon":"f…"fas fa-filter","target":"_self","title":""}]}]}]"}
responseText: "{"data":"[{\"text\":\"Home\",\"href\":\"http:\/\/home.com\",\"icon\":\"fas fa-home\",\"target\":\"_top\",\"title\":\"My Home\"},{\"text\":\"Opcion2\",\"href\":\"\",\"icon\":\"fas fa-chart-bar\",\"target\":\"_self\",\"title\":\"\"},{\"text\":\"Opcion3\",\"href\":\"\",\"icon\":\"fas fa-bell\",\"target\":\"_self\",\"title\":\"\"},{\"text\":\"Opcion4\",\"href\":\"\",\"icon\":\"fas fa-crop\",\"target\":\"_self\",\"title\":\"\"},{\"text\":\"Opcion5\",\"href\":\"\",\"icon\":\"fas fa-flask\",\"target\":\"_self\",\"title\":\"\"},{\"text\":\"Opcion6\",\"href\":\"\",\"icon\":\"fas fa-map-marker\",\"target\":\"_self\",\"title\":\"\"},{\"text\":\"Opcion7\",\"href\":\"\",\"icon\":\"fas fa-search\",\"target\":\"_self\",\"title\":\"\",\"children\":[{\"text\":\"Opcion7-1\",\"href\":\"\",\"icon\":\"fas fa-plug\",\"target\":\"_self\",\"title\":\"\",\"children\":[{\"text\":\"Opcion7-1-1\",\"href\":\"\",\"icon\":\"fas fa-filter\",\"target\":\"_self\",\"title\":\"\"}]}]}]"}"
setRequestHeader: ƒ (a,b)
state: ƒ ()
status: 200
statusCode: ƒ (a)
statusText: "OK"
success: ƒ ()
then: ƒ ()
__proto__: Object
现在,如何获得 responseText 值?
答案 0 :(得分:1)
随着您的ajax包装器返回ajax承诺,您可以在点击事件处理程序中使用与在包装器中完全相同的方式使用该承诺:
function _ajax_post(someData,URL)
{
var ajaxCall = $.ajax({
type: 'POST',
data: someData,
dataType: 'json',
url: URL
});
ajaxCall.done(function(data) {
console.log("global done");
});
return ajaxCall;
}
$('#btnOutput').on('click', function () {
var str = $("#out").text();
var r = _ajax_post({"data":str}, url+"roles/vu_menus/tets");
// at this point, r is the ajax promise, so can use .done / .fail etc
r.done(function(data) {
console.log(data);
});
});