dongzhao5970
dongzhao5970
2014-03-12 22:27

从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 dpdp42233 7年前

    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>
    
    点赞 评论 复制链接分享