现在已经浏览了SO几个小时,并尝试various proposed solutions类似问题,以便阅读official jQuery Docs,我仍然无法获得以下代码,并感谢任何帮助和提示我做错了什么。
我基本上尝试使用jQuery $ .ajax帖子将自定义JSON对象传递给PHP AJAX-Handler,但我的PHP脚本总是告诉我数据无效且不会执行。
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
SelectedSongNumber = indexPath.row
grabSong()
}
func grabSong () {
let songQuery = PFQuery(className: "Songs")
songQuery.getObjectInBackgroundWithId(iDArray[SelectedSongNumber], block: {
(object: PFObject?, error : NSError?) -> Void in
if let audioFile = object?["SongFile"] as? PFFile {
let audioFileUrlString: String = audioFile.url!
let audioFileUrl = NSURL(string: audioFileUrlString)!
myAVPlayer = AVPlayer(URL: audioFileUrl)
myAVPlayer.play()
currentUser?.setObject(audioFileUrlString, forKey: "CurrentSongURL")
currentUser?.saveInBackground()
}
})
}
有趣的是,当我记录“locationData”json-object时,它看起来很好:
function $('#linkButton').click(function(){
var latlng = '47.39220630060216,9.366854022435746';
var locationData = JSON.stringify({
from_mobile: '1',
location: latlng
});
$.ajax({
type: 'post',
url: 'ajax_handler.php',
data: locationData,
success: function (data) {
console.log(data); // returns 'Invalid location: ' from PHP
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + ' ' + errorThrown);
}
});
});
{"from_mobile":"1","location":"47.39220630060216,9.366854022435746"}
这里的任何人都可以发现我无法在PHP脚本中读取JSON值的问题吗?任何帮助都非常感谢!
答案 0 :(得分:0)
感谢@DarthGualin的评论和this SO answer我让它成功地改变了传递(JS)&解析(PHP)代码如下:
变化:
data: { jsonData: locationData },
完整代码:
function $('#linkButton').click(function(){
var latlng = '47.39220630060216,9.366854022435746';
var jsonData = JSON.stringify({
from_mobile: '1',
location: latlng
});
$.ajax({
type: 'post',
url: 'ajax_handler.php',
data: { jsonData: locationData },
success: function (data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + ' ' + errorThrown);
}
});
});
变化:
$data = json_decode($_POST['jsonData']); // Access Data Object
$mob = $data->{'from_mobile'}; // Access Value from json_data
完整代码:
$data = json_decode($_POST['jsonData']);
$mob = $data->{'from_mobile'};
$loc = str_replace(' ', '', $data->{'location'});
if(!empty($loc))
{
echo myClass::theClassMethod($mob, $loc);
} else {
exit('Invalid location: '.$loc);
}