我有一个ajax函数输出+1和-1的结果,在javascript中,我想获得在colorbox中使用的+1响应。 这是ajax函数:
function my_ajax_obj_lightbox() {
global $post;
if ( !empty( $_POST['obj_id'] ) ) {
$obj = new My_Obj( $_POST['obj_id'] );
if ( $obj instanceof My_Obj ) {
my_objs_ajax_response_string( 1, $obj->html() );
}
}
my_objs_ajax_response_string( -1, 'Invalid request' );
}
add_filter( 'wp_ajax_obj_lightbox', 'my_ajax_obj_lightbox' );
现在,在javascript中,我想说这样的话:
var response = ......;
if ( response[0] >= 1 ) {
j.fn.colorbox({
html: response[1],
maxWidth: '90%',
maxHeight: '90%'
});
}
如何定义var响应并将ajax响应作为值?
答案 0 :(得分:1)
听起来你需要帮助设置AJAX请求,并将响应解析为JavaScript对象......
假设您有一个PHP文件,它以JSON格式返回响应:
<?php
header('Content-type: application/json');
?>
[1, "<h2><?php echo $_POST['title'] ?></h2>"]
要使用AJAX检索此内容,您可以执行以下操作:
<script>
// Create the AJAX request object.
var request = new XMLHttpRequest();
// Define a function to handle the response.
request.onreadystatechange = function() {
// If the response is ready
if (request.readyState == 4 &&
request.status == 200) {
// Transform the response into a JavaScript object.
var response = eval(request.responseText);
/*
"response" is now a JavaScript array containing two values.
*/
console.log(response[0]);
/*
1
*/
console.log(response[1]);
/*
<h2>Hello World</h2>
*/
// Write the contents of the response to an element on the page.
if (response[0] >= 1) {
var div = document.createElement("div");
div.innerHTML = response[1];
document.body.appendChild(div);
}
}
};
// Define some variables that we want to send to the server.
var params = "foo=bar&baz=qux&title=" + encodeURIComponent("Hello World");
// Post the data, and load the response asynchronously.
request.open("POST", "/ajax-response.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);
</script>
如果你正在使用jQuery,这里是等效的代码:
<script>
$.post("/ajax-response.php", {
foo: "bar",
baz: "qux",
title: "Hello World"
},
function(response) {
if (response[0] >= 1) {
$("body").append(response[1]);
}
}
);
</script>
jQuery帖子的文档: http://api.jquery.com/jQuery.post/