0

我在使用 POST 方法的牛仔 REST 请求时遇到问题。如果通过提交表单内容完成 POST,它可以正常工作,但是当我使用 AJAX 将 POST 内容发送到服务器时它会响应。

错误响应是:415 Unsupported Media Type

这是我的 content_types_provided 和 content_types_accepted 代码

content_types_accepted(Req, State) ->
    Handler = [
        {<<"text/html">>, handle_post_html},
        {{<<"application">>,<<"json">>, []}, handle_post_html},
        {{<<"text">>, <<"plain">>, []}, handle_post_html}],
    {Handler, Req, State}.

content_types_provided(Req, State)->
    Handler = [
        {<<"text/html">>, parse_html},
        {<<"application/json">>, parse_json},
        {<<"text/plain">>, parse_plain_text}],
    {Handler, Req, State}.

任何机构对此案有任何想法?

4

2 回答 2

0

为了让牛仔理解通过 XMLHTTPRequest (AJAX) 方法 POST 发送的内容类型,需要在 JavaScript 中添加 headers 信息,如下所示:

<script language="javascript">
var content_types = {html:'text/html',json:'application/json',text:'text/plain',xml:'application/xml'};
    $(document).ready(function(){
        $('#btnPost').on('click', function(e){
            e.preventDefault();
            var href = 'http://localhost:8080/account-insert-12.html',
            var method = 'post',
            var resType = 'json'
            var postedData = $('#form').serialize();
            console.log(postedData);
            $.ajax({
                headers: {
                    'Accept': content_types[resType],
                    'Content-Type': content_types[resType] 
                },
                url:href, 
                type: method, 
                dataType: resType,
                data: postedData
            }).done(function(res){

            });
        });
    });
</script>
于 2015-08-04T02:11:11.983 回答
0

为什么要分开呢?

试试看:

content_types_accepted(Req, State) ->
    Handler = [
        {<<"text/html">>, handle_post_html},
        {<<"application/json">>, handle_post_html},
        {<<"text/plain">>, handle_post_html}],
    {Handler, Req, State}.

content_types_provided(Req, State)->
    Handler = [
        {<<"text/html">>, parse_html},
        {<<"application/json">>, parse_json},
        {<<"text/plain">>, parse_plain_text}],
    {Handler, Req, State}.
于 2015-08-04T01:25:52.417 回答