ajax - Vue JS Ajax 调用

标签 ajax wordpress vue.js vue-resource

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

编辑 - 这只会在通过 Wordpress 运行 Ajax 调用时导致错误。在 WP 之外,它确实有效。有什么想法吗??

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

        <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></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 调用可能遇到错误,您只处理成功的调用。请像这样扩展您的 sendAjax 函数:

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

现在应该提醒错误。

顺便说一句:最好使用 console.log() 而不是 alert(),它更具可读性,而且您不必确认每个警报.

关于ajax - Vue JS Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59118434/

相关文章:

javascript - 使用 firebase 并使用动态键名保存

php - 数据表连接表搜索和顺序卡在 codeigniter 上

javascript - Ajax 解析返回的 XML 时出错

angularjs - 将现有的 Angular Web 应用程序插入 WordPress 页面

css - 行内 block 元素被推到下一行

vue.js - nginx - 将 facebook/bots 代理到不同的服务器而不更改规范 URL

javascript - 如何使用javascript发出post请求

javascript - 如何在getcontenttools库中通过jquery发送ajax

html - 让 buddypress 管理栏固定在页面顶部

javascript - 具有相同自定义指令 vuejs 的多个元素