这是解析JSON的正确方法吗?

时间:2014-05-07 10:40:11

标签: jquery json wordpress

我是JSON,jQuery等世界的新手,但是当我看到如何使用jQuery通过JSON提供Wordpress内容的教程时,我很兴奋。直到我在本地计算机上运行代码。它应该读取已经插入JSON插件的Wordpress帖子,但是当我从浏览器中查看它时它什么也没有显示。

问题是:自教程发布以来,教程是否仍然有效或者jQuery协议是否已更改?问题是,这应该是我旅程中最简单的部分。如果我无法做到正确,本教程的其余部分将失去诚信,而男孩我想要做对了!

以下是代码:谢谢大家!

<!DOCTYPE HTML>
<html>
    <header>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script>
            function readSinglePost (url, target_div) {
                var URL = url
                jQuery.ajax({
                    url: URL,
                    dataType: 'json',
                    success: function(data) {
                        jQuery(target_div).html(data.post.content);
                    }
                });
            }

            jQuery(document).ready(function() {
                jQuery("#title").html("<h1>Hello World</h1>");
                // you might have to change this url
                varurl = "http://localhost/public_html/?json=get_post&dev=1&p=1";
                vartarget_div = "#contents";
                readSinglePost(url, target_div);
            });
        </script>
    </header>
    <body>
        <div id="main">
            <div id="title"></div>
        </div>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

听起来您正在从本地file://网址运行此页面。如果你是,AJAX请求不会起作用。您需要从服务器运行它。

编辑:哦,现在我看到了这个问题。您在var关键字和变量名称之间没有空格。

你也可以像这样简化readSinglePost函数:

       function readSinglePost (url, target_div) {
            jQuery.getJSON(url, function(data) {
// use the simple getJSON shortcut, and don't bother redefining the variable
                jQuery(target_div).html(data.post.content);
            });
        }

        jQuery(document).ready(function() {
            jQuery("#title").html("<h1>Hello World</h1>");
            // you might have to change this url
            var url = "localhost/Samples/sample1/?p=13115&json=1"; // public_html?
            var target_div = "#contents";
// you could even get rid of this and just pass the value directly on the next line:
// readSinglePost(url, "#contents");
// same thing with the url variable.
            readSinglePost(url, target_div);
        });
相关问题