wordpress ajaxurl获取骨干模型

Gee*_*ddy 2 javascript wordpress backbone.js

我正在学习Backbone.js并尝试基于它构建简单的主题.我在functions.php这个代码加载js:

    function load_js() {
      wp_enqueue_script('app-js', get_template_directory_uri() . '/app.js', array('backbone'));
      wp_localize_script('app-js', 'mechanics', array('ajaxurl' => admin_url('admin-ajax.php')));
    }

    add_action('wp_enqueue_scripts', 'load_js');
Run Code Online (Sandbox Code Playgroud)

在app.js这个简单的代码来获取帖子:

(function($){
    var Post = Backbone.Model.extend({});

    var Posts = Backbone.Collection.extend({
            model: Post,
            url: mechanics.ajaxurl
    });

    var new_posts = new Posts;
    new_posts.fetch();
})
Run Code Online (Sandbox Code Playgroud)

服务器端工作(我用jquery测试了它).如果认为问题是与url声明.有人能告诉我它应该是什么样子,或者jQuery ajax和Backbone同步网址之间是否存在差异?

工作jQuery版本

jQuery(document).ready(function() {
    var $ = jQuery;

    $.ajax({
    type: "GET",
    url: mechanics.ajaxurl,
    data: { action : 'mechanics_get_posts' },
    dataType: "json",
    success: function( response ) {
        alert( response );
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

Gee*_*ddy 6

我需要将数据添加到fetch函数.最终代码如下所示:

var Post = Backbone.Model.extend({});

var Posts = Backbone.Collection.extend({
    model: Post,
    url: mechanics.ajaxurl
});

var new_posts = new Posts;
new_posts.fetch({
    data: { action: 'mechanics_get_posts' }
});
Run Code Online (Sandbox Code Playgroud)