我知道之前已经问过这个问题,但我已经回顾了以前可以找到的所有帖子,但仍然无法使用它.希望问题很简单,你们可以帮我解决.
我无法从PHP脚本中获取一个数组,我将json_encoded返回到Javascript数组中.如果我删除dataType应该是json的条件,那么success函数会抱怨意外的数据.
我有一个Javascript函数,它使用POST方法调用PHP脚本.在PHP脚本中,我将一些调试消息写入日志文件并显示json_encoded数组的内容.当我使用JSONLint检查内容是否符合JSON但我的javascript函数总是出错.
<?PHP
// Include the PHP logger class so that we can write log messages to a log file
require_once('/myscripts/PHPlogger.PHP');
// Set up PHP log file
$log = new Logging();
$log->lfile('/mylogfiles/PHP-debug.log');
// Log status
$log->lwrite('Starting debug');
// ...
// (there's some more stuff here to get the data from a MysqL database)
// ...
// The following line when read in the log file shows a valid JSON array
$log->lwrite('array '.json_encode($dataVnvMethods));
$json_dataVnvMethods = json_encode($dataVnvMethods);
$log->lwrite('Ending debug');
?>
Javascript函数看起来像:
function jsgetvnvfilters(projid,repid,weekid)
{
$.ajax(
{
url: './getvnvfilter.PHP',
data: {'projid':projid, 'weekid':weekid, 'repid':repid},
type: 'post',
dataType: 'json',
success: function()
{
alert('success');
var prevnvlist = '<?PHP echo $json_dataVnvMethods ?>';
var vnvlist = JSON.parse(prevnvlist);
for (var x = 1; x <= vnvlist.length; x++) {
var vnv = vnvlist[x]['VnVMethod'];
vnvSel.options[vnvSel.options.length] = new Option(vnv, vnv);
}
},
error: function()
{
alert('failure');
}
}
);
}
解决方法:
你误解了javascript和PHP是如何相关的; PHP将在页面加载时仅呈现一次,因此您无法在javascript成功处理程序中回显返回的PHP数据.
相反,您的PHP脚本输出的所有内容都将在javascript变量中提供:
success: function(vnvlist) {
// ^^^^^^^ this is what has been outputted by PHP, the
// json already parsed
// your data is available in `vnvlist`
// var prevnvlist = '<?PHP echo $json_dataVnvMethods ?>';
// with dataType='json' you don't need to parse anything
// as jQuery will parse it for you
// var vnvlist = JSON.parse(prevnvlist);
// so all you need is this...
alert('success');
for (var x = 1; x <= vnvlist.length; x++) {
var vnv = vnvlist[x]['VnVMethod'];
vnvSel.options[vnvSel.options.length] = new Option(vnv, vnv);
}
},
...
// The following line when read in the log file shows a valid JSON array
$log->lwrite('array '.json_encode($dataVnvMethods));
// output your data so that it is available on the client-side
echo json_encode($dataVnvMethods);
$log->lwrite('Ending debug');
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。