Vue JS Ajax调用

问题描述 投票:0回答:2

我正在尝试从jQuery更改为Vue.js,并且在使用vueresource运行Ajax调用时遇到了一些困难。下面是我正在使用的jQuery和Vuejs的示例脚本。两者都试图访问相同的ajax调用。 jQuery调用有效,而vuejs调用无效。正在调用sendAjax方法,因为前两个警报显示-然后什么也不显示。

编辑-这仅在通过Wordpress运行Ajax调用时引起错误。在WP之外,它确实可以工作。有什么想法吗?

<!DOCTYPE html>
<html>
    <head>
        <title>Vue Resource</title>

        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    </head>

    <body>
        <button id="jQueryAjax">Jquery AJAX</button>

        <div id="myvue"> 
            <button @click.prevent="sendAjax()">AJAX</button>
        </div>

        <script>
            let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
            const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };

            Vue.use(VueResource);

            const ajax_app = new Vue({
                el: '#myvue',
                methods: {
                    sendAjax() {
                        alert("VueAjax");       
                        alert(JSON.stringify(postData));

                        this.$http.post(AjaxUrl, postData).then(res => {
                          alert(JSON.stringify(res));
                        });
                    }
                }
            });    

            $("#jQueryAjax").click(function() {
                alert("jQueryAjax");
                alert(JSON.stringify(postData));
                alert(AjaxUrl);

                $.ajax({
                    type: 'POST',
                    url: AjaxUrl,
                    data: postData,
                    dataType: 'json',
                    success: function(data) {
                        alert(JSON.stringify(data));
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("Error");
                    }
                });
            });
        </script>
    </body>
</html>
ajax wordpress vue.js vue-resource
2个回答
1
投票

您的AJAX呼叫可能遇到错误,您只能处理成功的呼叫。请像这样扩展您的sendAjax函数:

this.$http.post(AjaxUrl, postData).then(res => {
    alert(JSON.stringify(res));
}, err => {
    alert(err);
});

现在应该警告错误。

BTW:最好使用console.log()而不是alert(),因为它更具可读性,您不必确认每个警报。


0
投票

@ mbuechmann指出我能够看到实际的错误之后,我能够确定我遇到的问题实际上与Wordpress有关。为了使用Wordpress Ajax处理程序,您需要将操作发送到REQUEST标头。为此,您需要发送FormData,并且不发送标题。

在此问题中发现此代码:Custom Shortcode AJAX 400 Bad Request,使我能够使用Wordpress进行抓取。

var data = new FormData();

data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );

fetch(aj_ajax_demo.ajax_url, {
    method: 'POST',
    body: data, }).then(response => {
    if (response.ok) {
        response.json().then(response => {
            console.log(response);
        });
    } });
© www.soinside.com 2019 - 2024. All rights reserved.