使用ajax(wordpress)将表单从Jquery发送到PHP

问题描述:

我有一个javascript文件序列化并将表单发送到php函数:

I have a javascript file serializing and sending a form to the php function:

function call_ajax(){


var data2 = jQuery('#newIdeaForm').serialize(); // <--- Important

jQuery.ajax({
    type: 'POST',
    url: myAjax.ajaxurl,
    data: ({action : 'savedata',data : data2}),
    success: function() {


        alert(data2);


    }
});

};

问题是我不知道如何在这个php函数中接收这个表单:

The thing is that I don't know how to receive this form in this php function:

function savedata(){



$my_post = array(
            'post_title'    => 'data.name',
            'post_content'  => 'data.idea',
            'post_status'   => 'publish',
            'post_author'   => $user_id,
            );
        wp_insert_post($my_post);

        die();
    }

表格的某些字段是'name'和'idea',我知道var data2收到序列化的表单但不知道如何将这个表单放入php函数。

Some fields of the form are 'name' and 'idea', I know the var data2 receive the form serialized but don't know how to get this form into the php funcition.

其他问题:
在警报事件中它会警告序列化表单的javascript文件,如何反序列化此表单以仅提醒名称字段?

Other question: In the alert event of the javascript file it alerts the serialized form, how could I unserialize this form to alert just the name field?

serialize()将生成一个表单编码的字符串,如下所示:

serialize() will generate a form encoded string that looks like:

name = foo& email = foo @ bar.com& age = 86

如果您将对象传递给数据 jQuery默认会将它转换为这种格式。

If you pass an object to data jQuery will convert it to this format by default.

混合序列化和对象因此变得棘手,所以最好坚持使用一种方法或另一种方法。

Mixing serialize and object thus gets tricky so is best to to stick to one method or the other.

试试这个:

var data2 = jQuery('#newIdeaForm').serialize()
jQuery.ajax({
    type: 'POST',
    url: myAjax.ajaxurl,
    data: data2 + '&action=savedata',
    success: function() {
        .....

    }
});

现在您可以访问所有表格 name 使用 $ _ POST ['fieldName']

Now you can access all the form name's using $_POST['fieldName']