用jquery ajax传递json对象 [英] passing json object with jquery ajax

查看:182
本文介绍了用jquery ajax传递json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试回到基础,并通过ajax将JSON对象发送到我的php。当我收到JSON错误时,我甚至无法访问该部分。这是jquery代码:

Trying to go back to basics here and send a JSON object via ajax to my php. I can't even get to that part as I get a JSON error. Here is the jquery code:

jQuery(".deletebutton").on("click", function() {

        var employees = [
        { "firstName":"John" , "lastName":"Doe" },
        { "firstName":"Anna" , "lastName":"Smith" },
        { "firstName":"Peter" , "lastName": "Jones" }
        ];

        var dataString = JSON.stringify(employees);

        // Lets put our stringified json into a variable for posting
        var postArray = {json:dataString};

        jQuery.ajax({
            type: 'POST',
            url: 'index.php?option=com_recordings&task=deletevideos&format=raw',
            data: postArray,
            dataType: 'json',
            success: function(data){
                if (data == "blah")
                    alert(data);

            }
        });
});

我收到此错误(当我检查 errorThrown ):SyntaxError:JSON.parse:意外字符。我用jsonlint.com查看它是有效的JSON。我做错了什么?

I get this error (when I check errorThrown): SyntaxError: JSON.parse: unexpected character. I checked with jsonlint.com that it is valid JSON. What am I doing wrong?

推荐答案

dataType 指的是请求标头,而不是响应。如果你没有发回有效的JSON,jQuery将不喜欢它。你想发送JSON,但你可能想要找回别的东西。只需删除 dataType ,它就可以正常工作,除非服务器脚本出错。

dataType refers to the request header, not the response. If you are not sending back valid JSON, jQuery won't like it. You want to send JSON, but you probably want to get back something else. Just remove dataType and it should work properly, unless there's an error on the server script.

这篇关于用jquery ajax传递json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆