Admin Ajax and HTML5 Formdata

时间:2017-03-03 作者:evu

在Wordpress Admin Ajax中使用FormData时,我只得到一个“0”响应。通常这是因为没有动作,但是我包含了动作,仍然存在问题。我在这里看到过类似的问题,但它们都假设正在使用jQuery,而在我的情况下则不是。

Javascript:

            if ($this.valid()) {

                var form_data = new FormData(form);
                form_data.append(\'security\', WP.nonce);
                form_data.append(\'action\', form.action);

                console.log(form.action); // console shows http://test.dev/newsletter_signup

                u.jax.post(WP.ajax, form_data, onSent);

                function onSent(result) {
                    if (result.success) {
                        $this.html(\'<p class="form-sent">\' + $this.data(\'success\') + \'</p>\');
                    } else {
                        $this.html(\'<p class="form-sent">\' + result.data + \'</p>\');
                    }
                }
            }
PHP:

add_action(\'wp_ajax_newsletter_signup\',         \'newsletter_signup\');
add_action(\'wp_ajax_nopriv_newsletter_signup\',  \'newsletter_signup\');
HTML:

<form action="newsletter_signup" class="newsletter-signup js-process-form" autocomplete="off">
        <div class="field">
            <label for="newsletter-email" class="field__label">Your Email Address</label>
            <input type="email" class="field__input" name="email-address" id="newsletter-email" required data-msg-required="We need to know your email address" value="[email protected]">
            <button type="submit" class="field__button">submit</button>
        </div>

    </form>
我能看到的唯一问题是,该操作将域附加到它之前。如果我使用jquery ajax来实现这一点,那么它工作得很好,因此代码似乎只有javascript。我可以提供ajax函数,但它们非常通用。

如果您还需要任何代码,请告诉我。

谢谢

Edit for comments:

我已尝试将表单更改为注释中提到的隐藏操作输入字段:

<form action="">
        <input type="hidden" name="action" value="newsletter_signup"/>

        <div class="field">
            <label>Your Email Address</label>
            <input type="email" name="email-address">
            <button type="submit">submit</button>
        </div>

    </form>
这是提交时发送的formdata:

------WebKitFormBoundarycskAgc8KcinCzpoG
Content-Disposition: form-data; name:"action"

newsletter_signup
------WebKitFormBoundarycskAgc8KcinCzpoG
Content-Disposition: form-data; name="email-address"

[email protected]
------WebKitFormBoundarycskAgc8KcinCzpoG--
它被发送到:

http://test.dev/wp-admin/admin-ajax.php

Edit #2:

发送get请求,如:

u.jax.get(\'http://test.dev/wp-admin/admin-ajax.php?action=newsletter_si‌​gnup&email-address=t‌​[email protected]\', function(s){
                console.log(s)
            });
还导致响应0.

以下是我的js ajax函数,以便于更清晰地理解:

// ===== Ajax Utilities
// Handles Ajax Responses
function _handleResponse(request, success) {
    request.onreadystatechange = function() {
        if (request.status >= 200 && request.status < 400) {

            if (typeof request.responseText == \'string\') {
                data = request.responseText;
            } else {
                data = JSON.parse(request.responseText);
            }

            success(data);

        } else {
            return request.status + \' failed request: \'+ JSON.parse(request.responseText);
        }
    };

    request.onerror = function() {
        return request.status + \' failed request: \'+ JSON.parse(request.responseText);
    };
}

// Ajax GET & POST
u.jax = {
    get: function(url, success) {
        var request = new XMLHttpRequest();

        request.open(\'GET\', url, true);
        request.send(null);

        _handleResponse(request, success);

    },
    post: function(url, data, success) {
        var request = new XMLHttpRequest();

        request.open(\'POST\', url, true);
        request.setRequestHeader(\'Content-Type\', \'application/x-www-form-urlencoded; charset=UTF-8\');
        request.send(data);

        _handleResponse(request, success);
    }
};
get请求的邮递员标头:

Cache-Control →no-cache, must-revalidate, max-age=0
Connection →Keep-Alive
Content-Length →1
Content-Type →text/html; charset=UTF-8
Date →Fri, 03 Mar 2017 16:16:54 GMT
Expires →Wed, 11 Jan 1984 05:00:00 GMT
Keep-Alive →timeout=5, max=100
Server →Apache/2.4.20 (Unix) PHP/5.5.35 mod_wsgi/3.5 Python/3.5.1 OpenSSL/1.0.1p
X-Content-Type-Options →nosniff
X-Frame-Options →SAMEORIGIN
X-Powered-By →PHP/5.5.35
X-Robots-Tag →noindex

2 个回复
最合适的回答,由SO网友:evu 整理而成

因此,唯一的问题是标题内容类型。

通过删除request.setRequestHeader(\'Content-Type\', \'application/x-www-form-urlencoded; charset=UTF-8\'); 把它放在一边,效果很好。这也是表单动作被抓取和附加的原因。

Ajax调用:

var formData = new FormData(form);
formData.append(\'security\', WP.nonce);
formData.append(\'action\', form.getAttribute(\'action\'));

u.jax.post(WP.ajax, formData, onSent);
Ajax功能:

u.jax.post = function(url, data, success) {
    var request = new XMLHttpRequest();

    request.open(\'POST\', url, true);
    request.send(data);

    request.onreadystatechange = function() {
        if (request.readyState === 4) {

            if (typeof request.responseText == \'string\') {
                data = request.responseText;
            } else {
                data = JSON.parse(request.responseText);
            }

            success(data);
            return;

        }
    };
}
形式:

<form action="newsletter_signup">

    <div class="field">
        <label>Your Email Address</label>
        <input type="email" name="email-address">
        <button type="submit">submit</button>
    </div>

</form>
PHP:

function newsletter_signup(){

    // Get the email address
    $email = sanitize_email($_POST[\'email-address\']);

    // Do what you wish with the email address.

    //Setup the data to send back
    $data = array();

    // json encode the data to send back
    echo json_encode($data);
    exit;

}

add_action(\'wp_ajax_newsletter_signup\',         \'newsletter_signup\');
add_action(\'wp_ajax_nopriv_newsletter_signup\',  \'newsletter_signup\');

SO网友:Spartacus

FormData将表单标记的操作作为表单数据的一部分进行处理,而这不是您想要发送给admin ajax的内容。php。尝试另一种方式将“新闻稿\\u注册”作为操作发送给admin ajax。php,主要通过构建自己的数组:

var form_data = new FormData(form);
    form_data.append(\'security\', WP.nonce);
    form_data.append(\'value\', form.value);
    // etc. etc., for each value you want to send

var formData = {

    action: \'newsletter_signup\',
    data: form_data

}

u.jax.post(WP.ajax, formData, onSent);
还有,是什么发送了0?是管理ajax。php,还是die() 在处理表单数据的php脚本中的某个地方?

相关推荐

WordPress AJAX错误400向远程站点发送数据的错误请求

我正在使用发件人。net获取电子邮件订阅列表。这个网站给了我一些信息,可以将用户的电子邮件添加到订阅列表中。我想使用WordPress ajax来实现这一点。但它返回错误400错误请求。我的代码是:文件ajax新闻脚本。js公司: jQuery(document).ready(function($){ // Perform AJAX send news on form submit $(\'form#fnews\').on(\'submit\', funct