dongzhao5970 2014-03-12 22:27
浏览 22
已采纳

从jquery读取POST集

I am new to this so sorry if I have a hard time asking this question or my terminology is not correct. I have a very simple web service that takes a json string, does some stuff, then echos a result in json:

$jsonStr = '';

if(isset($_POST['request']))
{
    $request = $_POST['request'];
    $jsonStr = parseJsonStr($request);
}
else //nothing posted return failed
    $jsonStr = '{"Result" : "Failed No Data", "Code" : 400}';

$resultsArr = json_decode($jsonStr, true);

if(array_key_exists('Code', $resultsArr))
{
    $http_response_code = array(
        200 => 'OK',
        201 => 'CREATED',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        403 => 'Forbidden',
        404 => 'Not Found',
        500 => 'Internal Error',
        501 => 'Not implemented'
    );

    header('HTTP/1.1 '.$resultsArr['Code'].' '.$http_response_code[ $resultsArr['Code'] ]);
}

header('Content-Type: application/json');
echo($jsonStr);

Using php and curl I can post to it and it works:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('request' => $jsonStr ));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status >= 300 ) //I expect mostly 201
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));

curl_close($curl);
echo($json_response);

I am trying to do the same post with jQuery .ajax, but I am having trouble getting it to post to the 'request' field Here is what I have so far:

//edit I didn't include this on my original post 
var jsonStr = '{"userName":"' + $('input[name="username"]').val() + '",' + '"password":"' + $('input[name="pwd"]').val() ...
//end edit
$.ajax(
{ // ajax call starts
    type: "POST",
    url: url,
    data: JSON.stringify({ request: jsonStr }),
    contentType: "application/json; charset=utf-8",
    success: function(data)
    {
        $('#retJson').html(''); // Clear #retJson div
        $('#retJson').append('<br/>' + data + '<br/>');
    },
    error: function(data, errorThrown)
    { 
        $('#retJson').html(''); // Clear #retJson div
        $('#retJson').append('data:' + data +  ' errorThrown: ' + errorThrown); 
    } 
});

I am getting my 'Failed No Data error' so I know that it is connecting to it, but I don't think it is posting anything. Any help would be much appreciated.

EDIT

I figured out my issue which lead to another question it works if I changed to this:

$.ajax(
{ // ajax call starts
    type: "POST",
    url: url,
    data: 
    { 
        request: '{"userName":"' + $('input[name="username"]').val() + '",' + '"password":"' + $('input[name="pwd"]').val() ...
    },
    contentType: "application/json; charset=utf-8",
    success: function(data)
    {
        $('#retJson').html(''); // Clear #retJson div
        $('#retJson').append('<br/>' + data + '<br/>');
    },
    error: function(data, errorThrown)
    { 
        $('#retJson').html(''); // Clear #retJson div
        $('#retJson').append('data:' + data +  ' errorThrown: ' + errorThrown); 
    } 
});

My question is how do I use a var in the .ajax?

  • 写回答

1条回答 默认 最新

  • dpdp42233 2014-03-12 22:37
    关注

    I've created a PHP and HTML file to test the entire use case.

    <?php
    
        function parseJsonStr($request) {
            if(get_magic_quotes_gpc()) {
                $request = stripslashes($request);
            }
            return '{"Code":200}';
        }
    
        $jsonStr = '';
    
        if(isset($_POST['request'])) {
            $request = $_POST['request'];
            $jsonStr = parseJsonStr($request);
        } else {
    
            //nothing posted return failed
            $jsonStr = '{"Result" : "Failed No Data", "Code" : 400}';
        }
    
        $resultsArr = json_decode($jsonStr, true);
    
        if(array_key_exists('Code', $resultsArr)) {
            $http_response_code = array(
                200 => 'OK',
                201 => 'CREATED',
                400 => 'Bad Request',
                401 => 'Unauthorized',
                403 => 'Forbidden',
                404 => 'Not Found',
                500 => 'Internal Error',
                501 => 'Not implemented'
            );
    
            header('HTTP/1.1 '.$resultsArr['Code'].' '.
                $http_response_code[$resultsArr['Code'] ]);
        }
    
        header('Content-Type: application/json');
        echo($jsonStr);
        die();
    ?>
    

    There are the contents of the HTML file.

    <html>
        <head>
            <script src="http://code.jquery.com/jquery-git1.js"></script>
            <script>
    
            var jsonStr = '{"dummyRequest":true}';
    
            // ajax call starts
            $.ajax({ 
                type: "POST",
                url: 'data.php',
                data: {
                    request: jsonStr
                },
                success: function(data) {
    
                    if (typeof data == 'string') {
                        data = $.parseJSON(data);
                    }
    
                    $('#retJson').html(''); // Clear #retJson div
                    $('#retJson').append('data = {<br />');
                    for (var key in data) {
                        $('#retJson').append(key + ': ' + data[key] + '<br />');
                    }
                    $('#retJson').append('}');
                },
                error: function(jqXHR, textStatus, errorThrown) {
    
                    $('#retJson').html(''); // Clear #retJson div
                    $('#retJson').append('error = ' + errorThrown); 
                } 
            });
            </script>
        </head>
        <body>
            <div id="retJson">
            </div>
        </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记