使用JQuery和amp;发送包含输入和文件的表单数据AJAX到PHP Web服务

时间:2015-06-22 19:16:09

标签: javascript php jquery ajax

我试图将我的表单中的所有数据与Jquery和Ajax一起发送到PHP REST Web服务。

JS

$("#idform").submit(function(event) {

/* Stop form from submitting normally */
event.preventDefault();

//Get Data
var form = $(this),  
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method');

/* Send the data using post and put the results in a div */
$.ajax({
    url: formUrl,
    type: formMethod,
    data: formData,
    dataType: "json",
    //processData: false,  // tell jQuery not to process the data
    //contentType: false   // tell jQuery not to set contentType
    success: function(res){
        if (res.result == '0') {
                $("#idform").html('<div class="text-lg">Good Job!</div>');
            } else {
                //$("#respuesta").html('Error:');
                $("#respuesta").html(res.message);
            }     
    },
    error:function(res){
        $("#respuesta").html('Error comunicating webservice');
    }
});

});

PHP 我用文件做这样的事情:

if($_SERVER['REQUEST_METHOD'] == 'POST'){ 
$fileuploaded = $_FILES['fileuploaded']['tmp_name'];
$destinationpath = $_SERVER['DOCUMENT_ROOT']."/path/".$_FILES['fileuploaded']['name'];
move_uploaded_file($fileuploaded, $destinationpath);}

当我从表单直接发布到php文件时,Everythings就可以了,但是当我尝试使用ajax发送数据时却没有。 PHP Web服务收到所有输入但没有我的两个文件:(

抱歉写英文不好!

1 个答案:

答案 0 :(得分:0)

我认为你必须像这样使用JS

<强> JS

$.ajax({
        url: "web_service.php",
        data:'value1=1&value2='+$("#num").html()+'&value3=G',
        cache: false,
        async : true,
        type: "POST",
        ....

在doc.php中,您可以使用PHP连接到Web服务的代码以及上面数据行中发送的参数。数据就是一个例子