2014-03-12 3 views
0

새로운 질문입니다.이 질문을하거나 내 전문 용어를 잘못 입력하면 죄송합니다. 나는 다음 몇 가지 물건 JSON의 결과 메아리 않는, JSON 문자열이 걸리는 매우 간단한 웹 서비스를 : PHP를 사용jquery에서 POST 세트 읽기

$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); 

를 내가 여기에 게시 할 수 곱슬 곱슬하고 그것을 작동 :

$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); 
나는 '내 무엇입니까

//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); 
    } 
}); 

:

나는의 jQuery 아약스와 같은 게시물을하려고하지만, 나는 그것이'요청 '다음 필드 에 게시하는데 문제가 오전은 내가 지금까지 무엇을 가지고 실패한 No Data error '라는 메시지가 표시되어 연결되는 것으로 알고 있지만 게시하는 것으로는 생각하지 않습니다. 어떤 도움이라도 대단히 감사 할 것입니다.

내가이로 변경 한 경우 작동 다른 질문으로 이어질 내 문제를 파악

편집 :

$.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); 
    } 
}); 

내 질문에 나는 아약스에서 VAR을 사용합니까 어떻게?

+0

'$ .ajax' 호출에서'dataType : 'json''을 옵션으로 설정하면 어떻게됩니까? –

+0

같은 일을합니다. – Tbone

답변

1

전체 사용 사례를 테스트하기 위해 PHP 및 HTML 파일을 만들었습니다.

<?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(); 
?> 

HTML 파일의 내용이 있습니다.

<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> 
+0

그래도 작동하지 않습니다. 실패한 데이터가 아직 없습니다. – Tbone

+1

전체 사용 사례를 테스트하고 코드를 업데이트했습니다. –

+0

감사합니다! 그게 많은 도움이됩니다! – Tbone

관련 문제