[英]How to select ajax response to use in colorbox javascript?
我有一个 ajax function 在 javascript 中输出 +1 和 -1 的结果,我想获得 +1 响应以在颜色框中使用。 这是 ajax function:
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 响应作为值?
听起来您只需要帮助设置 AJAX 请求,并将响应解析为 JavaScript object ...
假设您有一个 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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.