我试图使用jQuery的上传插件。 http://valums.com/ajax-upload/
当我将返回的响应类型设置为json时,firefox将弹出一个对话框,询问我如何处理返回的json对象。
人们在上传脚本的作者页面上提出了同样的问题但到目前为止还没有回答。希望这里的javascript人员可以弄清楚我们如何处理这个问题。
感谢。
<script type= "text/javascript">
/*<![CDATA[*/
$(document).ready(function(){
/* example 1 */
var button = $('#button1'), interval;
new AjaxUpload(button, {
//action: 'upload-test.php', // I disabled uploads in this example for security reasons
action: '/posts/upload_images/',
name: 'myfile',
responseType: 'json',
onSubmit : function(file, ext){
// change button text, when user selects file
button.text('Uploading');
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function(){
var text = button.text();
if (text.length < 13){
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response){
var json = response;
alert(json);
button.text('Upload');
window.clearInterval(interval);
// enable upload button
this.enable();
// add file to the list
// $('<li></li>').appendTo('#example1 .files').text(json.response_text);
$('<li></li>').appendTo('#example1 .files').text(file);
}
});
});
/*]]>*/
</script>
答案 0 :(得分:2)
http://api.jquery.com/jQuery.parseJSON/
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
答案 1 :(得分:1)
这个jQuery插件可以很容易地转换为JSON:http://code.google.com/p/jquery-json/
另外,您可能对您引用的博客文章中的this comment感兴趣:
很抱歉发布你的博客文章(这很棒),但我想我会提到我发现了问题:
无论出于何种原因,当响应类型为
<pre>
时,响应始终在整个响应周围都有plain/text
个标记。这导致eval()
调用失败。我目前的解决方案是在eval()
调用之前删除这些标记,现在一切正常。不是一个很好的解决方案,但至少我现在可以继续工作。
答案 2 :(得分:0)
这可能是它,我不知道,因为我对该插件一无所知,但您可能需要查看您在服务器端设置的响应类型;您应该将HTTP响应设置为具有“text / plain”,“text / javascript”或“application / javascript”之类的内容/ MIME类型 - 看看是否能解决您的问题。
答案 3 :(得分:0)
我正在为同一个脚本寻找解决方案,偶然发现了这个页面。我没有在网上找到解决方案所以这就是我修复它的方法:
@ upload-file.php
:
替换
echo "success".$cc;
与
echo json_encode(array(
status' => 'success',
'id' => $picid,
'image' => $imgurl
));
@ front end
:
取代
var bb=response.substr(0,7)
var idd=response.replace('success',' ');
var idb =idd.replace(/^\s*|\s*$/g,'');
if(bb==="success")
{
$('<span></span>').appendTo('#files').html('<img src="images/'+file+'" alt="" width="120" height="120" style="margin:5px;" />').addClass('success');
}
else
{
$('<span></span>').appendTo('#files').text(file).addClass('error');
}
与
var what = jQuery.parseJSON(response);
if(what.status == 'success')
{
$('<span id='+what.id+'></span>').appendTo('#files').html('<img src="'+what.image+'" alt="" width="120" height="120" style="margin:5px;" /><br><a href="javascript:void(0)" onClick="deleteFile('+what.id+');">Delete</a>').addClass('success');
}
else
{
$('<span></span>').appendTo('#files').text(response).addClass('error');
}
并实际回答这个问题。
jQuery.parseJSON(response);
确实..