jQuery.ajax to $http

jQuery.ajax to $http

本文关键字:http to ajax jQuery      更新时间:2023-09-26

我使用了这个函数

    jQuery.ajax({
        type: 'POST',
        url: urlSubmit,
        timeout: 5000,
        dataType: 'text',
        data: {
            date : dataDate,
            url : dataUrl,
            domaine : dataDomaine,
            email : dataEmail,
            destinataire : dataDestinataire,
            msg : dataMsg
        },
        "success": function (jqXHR, textStatus, errorThrown) {
            console.log("AJAX success :) - statut " + textStatus);
            $timeout(successMailZR_alerte, 3000);
        },
        "error": function (jqXHR, textStatus, errorThrown) {
            console.log("AJAX fail :/ - statut " + textStatus);
            $timeout(errorMailZR_alerte, 3000);
        }
    });

代码在做什么:将POST代码发送给发送电子邮件的php脚本。

但是,由于我在一个完整的angularjs应用程序中重写了我的代码,我这样做:

    $http({
        method: 'POST',
        url: urlSubmit,
        timeout: 5000,
        cache: false,
        data: {
            date : dataDate,
            url : dataUrl,
            domaine : dataDomaine,
            email : dataEmail,
            destinataire : dataDestinataire,
            msg : dataMsg
        },
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        responseType: 'text',
    }).
    success(function(data, status, headers, config) {
        console.log("AJAX success :) - statut " + status);
        $timeout(successMailZR_alerte, 3000);
    }).
    error(function(data, status, headers, config) {
        console.log("AJAX fail :/ - statut " + status);
        $timeout(errorMailZR_alerte, 3000);
    });

问题是:有了$http,我成功了200,但什么都没有发布,我的电子邮件也没有回复。怎么了?

问题是jQuery的POST确实将数据作为表单数据(例如键值对)发送(https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_and_retrieving_form_data)而AngularJS在请求有效载荷中发送您的数据。关于两者之间的区别,请参阅以下SO问题:What';s;请求有效载荷";vs";表单数据";如Chrome开发工具"网络"选项卡中所示

为了使您的angular脚本与服务器协同工作,您必须将数据转换为URL编码的字符串,如下所述:如何将数据作为表单数据而不是请求负载发布?。仅仅设置headers: {'Content-Type': 'application/x-www-form-urlencoded'}是不够的。

另一种方法是调整应用程序的后端以解析消息负载,而不是表单数据参数。

要理解这一点,需要理解angularjquery设置的请求标头。与标头之间存在差异,例如当请求由jQuery发布时,标头可能如下所示:

POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded // default header set by jQuery
foo=bar&name=John

您可以在浏览器中的请求中以表单数据的形式看到这一点,如果您使用chrome,则可以在网络选项卡的chrome检查器中看到这一情况,如果您单击请求,则可以看到由jQuery设置的form data和内容标题。

在angular js $http服务的另一边,当发出请求时,您可以找到以下内容:

POST /some-path HTTP/1.1
Content-Type: application/json // default header set by angular

{ "foo" : "bar", "name" : "John" }

真正的区别是您有一个request payload,而不是jQuery使用的常见form data。所以你需要在服务器端做一些额外的事情,如下所示。

使用此:

$data = json_decode(file_get_contents("php://input"));
echo $data->date;
// and all other params you have sent

这是由于其默认标头

  • 接受:application/json、text/plain、*/*
  • 内容类型:application/json

jQuery不太可能有其他东西:

  • 内容类型:application/x-www-form-urlencoded;charset=UTF-8