如何将JSON输出检索到JavaScript变量中?

时间:2012-11-07 11:36:40

标签: php javascript jquery ajax json

我的jsonOutput.php页面如下:

 $response['imgsrc'] =  $filename[1];
 echo json_encode($response);

输出{"imgsrc":"071112164139.jpg"}

等文件名

现在我的问题是,如何在index.php中使用jQuery使用ajax将文件名转换为变量?

4 个答案:

答案 0 :(得分:2)

$.getJSON('jsonOutput.php', function(data) {
  var filename = data.imagesrc;
});

答案 1 :(得分:2)

试试这个:

$.get('<your php file>', {}, function(response) {
   var imagesrc = response.imgsrc;
   alert(response.imgsrc);
});

阅读http://api.jquery.com/jQuery.get/

答案 2 :(得分:1)

您所要做的就是执行jQuery ajax调用 -

var imgSrc = '';
$.ajax(PATH_TO_PHP_SCRIPT,{},function(response){
  imgSrc = response.imgsrc;
},'json');

您的imgsrc参数现在将成为名为imgSrc的JavaScript变量。不要忘记指定您的dataTypejson

参考 -

答案 3 :(得分:1)

您可以使用jQuery.parseJSON将json输出解析为javascript对象。

以下代码可行:

var json = json_encode(<?php echo $response ?>);
var obj = jQuery.parseJSON(json);
alert("file name is: " + obj.imgsrc);
相关问题