0
返回NULL這裏是我正在爲我的WordPress網站代碼:jQuery的AJAX請求從PHP
的jQuery:
jQuery(document).ready(function($)
{
var actionValue;
$(".tabRow li").on('click', function(event)
{
event.preventDefault(); //override default behaviour
var clicked = $(this); //caches click so we don't scan DOM again
if(clicked.attr('id')=="tabAddData") //tab1 clicked
{
actionValue = "tab1Clicked";
}
$("li").removeClass("selected");
clicked.addClass("selected");
alert ('starting ajax call');
$.ajax(
ajaxObject.ajaxurl, //request gets sent to this url
{ //start of [options]
type: 'POST',
dataType: 'json', //type of data expected back from server
//data to send to server (JSON format)
data:
{
action: 'ajaxAction',
nonce: ajaxObject.nonce,
actionName: actionValue
}
} //end of [options]
) //end ajax(), the other fuctions are chained to it (.done .fail .always)
.done (function(data)
{
alert ('success function');
if(actionValue == "tab1Clicked") //tab1 clicked
{
$('#dataSection').empty();
$('#dataSection').append(data);
}
}) //end of done (success) function
.fail (function(xhr, desc, err)
{
alert ('error function');
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}) //end of fail (error) function
}); //end of onclick
});
PHP:
<?php
$my_action='ajaxAction';
if(defined('DOING_AJAX') && DOING_AJAX)//check if AJAX is loaded and working
{
//for logged in users
add_action('wp_ajax_'.$my_action, 'ajaxResponse');
}
function ajaxResponse()
{
if(wp_verify_nonce($_POST['nonce'], 'ajaxAction'))
{
if($_POST['actionName'] == "tab1Clicked")
{
$addDataSection = getAddDataSection();
$response=array(
'status' => 'success',
'addDataSection' => $addDataSection
);
header('Content-type:application/json;charset=utf-8');
echo json_encode($response);//encodes the jQuery array into json format
die;
}
}
}
function getAddDataSection()
{
//lots of echo statements which builds the html code
}
?>
當我第一次加載我的頁面,我的PHP函數getAddDataSection()
生成我的<div id='dataSection>
。這工作正常。
當我點擊tab1時,我的jQuery AJAX調用應該重用相同的PHP函數來生成我的HTML。這是不是工作正常。
當我點擊tab1後,觸發了jQuery失敗函數。
當我檢查螢火蟲,響應數據包含我的PHP函數getDataSection()
生成的HTML,其次是JSON字符串
{"status":"success","addDataSection":null}
回答時,請記住我是一個新手。謝謝:)
更新包括控制檯錯誤:
Details: parsererror
Error:SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
詳情:parsererror 錯誤:語法錯誤:JSON.parse:在第2行的第1列意外的字符JSON數據 – liverpaul