admin管理员组

文章数量:1357678

I want my response to be in JSON Object. But in some functions it es as string and I want to parse it. How can I achieve this? This is my function.

function serverRequest(requestDATA, successCallback, errorCallback, hideIndicator, showAlert){
    var METHOD = "POST";
    var serverURL = '.php'; //Path to Server.php
    //var serverURL = 'http://localhost/istudy/server.php'; //Path to Server.php
    var DATA_TYPE = 'json';
    var TIMEOUT = 20000;
    console.log(requestDATA);
    $$.ajax({
        url: serverURL,
        data: requestDATA,
        dataType: DATA_TYPE,
        type: METHOD,
        timeout: TIMEOUT,
        success: function(data){
            successCallback(data, hideIndicator, showAlert);
        },
        error: function(a, b, c){
            errorCallback(a, b, c, hideIndicator, showAlert);
        }
    }); 
}

And this is my responseText

responseText: "{"status":"success","message":"Your Order has Processed. Please Note this pin <b style=\"background-color:green;\">osIyKvAp<\/b> and send it to the admin with payment details."}"

THIS IS MY PHP FUNCTION

function confirm_order($id, $newarray, $cn) {
    $today = date('y-m-d');
    $expiry = date('Y-m-d', strtotime("+30 days"));
    $total_items = 0;
    $total_price = 0;
    foreach ($newarray as $key => $val) {
        $total_items++;
        foreach ($val as $doc) {
            $total_price = $total_price + $doc->doc_price;
        }
    }

    $pin = random_string('alnum', 8);

    $sql = "INSERT INTO orders (order_id, order_UserId, order_total_items, order_amount, date_created,order_status,order_pin)
    VALUES ('', '" . $id . "', '" . $total_items . "', '" . $total_price . "', '" . $today . "','0','" . $pin . "')";

    if (mysqli_query($cn, $sql)) {
        $order_id = mysqli_insert_id($cn);

        foreach ($newarray as $key => $val) {
            $total_docs = 0;
            $total_items++;
            $sep = '|';
            $sub_price = 0;
            $doc_list = '';
            foreach ($val as $doc) {
                $doc_list .= $doc->doc_id . $sep;
                $sub_price = $sub_price + $doc->doc_price;
                $total_docs++;
                $sep = '|';
            }

            $sql = "INSERT INTO cart_items (uc_id, uc_user_id, uc_course_id, uc_course_docs_id, uc_course_docs_num,uc_price,uc_order_num,uc_order_status,uc_dateBuy,uc_dateExpire)
            VALUES ('', '" . $id . "', '" . $key . "', '" . $doc_list . "', '" . $total_docs . "','" . $sub_price . "','" . $order_id . "','0','" . $today . "','" . $expiry . "')";

            mysqli_query($cn, $sql);
        }

        $response_array['status'] = 'success';
        $response_array['message'] = 'Your Order has Processed. Please Note this pin <b style="background-color:green;">' . $pin . '</b> and send it to the admin with payment details.';
    } else {
        $response_array['status'] = 'error';
        $response_array['message'] = 'An error occurred. Please try again later.';
    }
    echo json_encode($response_array);
}

Can I place any check to JSON.parse if and only if my response is string?

I want my response to be in JSON Object. But in some functions it es as string and I want to parse it. How can I achieve this? This is my function.

function serverRequest(requestDATA, successCallback, errorCallback, hideIndicator, showAlert){
    var METHOD = "POST";
    var serverURL = 'http://istudy..pk/api/server.php'; //Path to Server.php
    //var serverURL = 'http://localhost/istudy/server.php'; //Path to Server.php
    var DATA_TYPE = 'json';
    var TIMEOUT = 20000;
    console.log(requestDATA);
    $$.ajax({
        url: serverURL,
        data: requestDATA,
        dataType: DATA_TYPE,
        type: METHOD,
        timeout: TIMEOUT,
        success: function(data){
            successCallback(data, hideIndicator, showAlert);
        },
        error: function(a, b, c){
            errorCallback(a, b, c, hideIndicator, showAlert);
        }
    }); 
}

And this is my responseText

responseText: "{"status":"success","message":"Your Order has Processed. Please Note this pin <b style=\"background-color:green;\">osIyKvAp<\/b> and send it to the admin with payment details."}"

THIS IS MY PHP FUNCTION

function confirm_order($id, $newarray, $cn) {
    $today = date('y-m-d');
    $expiry = date('Y-m-d', strtotime("+30 days"));
    $total_items = 0;
    $total_price = 0;
    foreach ($newarray as $key => $val) {
        $total_items++;
        foreach ($val as $doc) {
            $total_price = $total_price + $doc->doc_price;
        }
    }

    $pin = random_string('alnum', 8);

    $sql = "INSERT INTO orders (order_id, order_UserId, order_total_items, order_amount, date_created,order_status,order_pin)
    VALUES ('', '" . $id . "', '" . $total_items . "', '" . $total_price . "', '" . $today . "','0','" . $pin . "')";

    if (mysqli_query($cn, $sql)) {
        $order_id = mysqli_insert_id($cn);

        foreach ($newarray as $key => $val) {
            $total_docs = 0;
            $total_items++;
            $sep = '|';
            $sub_price = 0;
            $doc_list = '';
            foreach ($val as $doc) {
                $doc_list .= $doc->doc_id . $sep;
                $sub_price = $sub_price + $doc->doc_price;
                $total_docs++;
                $sep = '|';
            }

            $sql = "INSERT INTO cart_items (uc_id, uc_user_id, uc_course_id, uc_course_docs_id, uc_course_docs_num,uc_price,uc_order_num,uc_order_status,uc_dateBuy,uc_dateExpire)
            VALUES ('', '" . $id . "', '" . $key . "', '" . $doc_list . "', '" . $total_docs . "','" . $sub_price . "','" . $order_id . "','0','" . $today . "','" . $expiry . "')";

            mysqli_query($cn, $sql);
        }

        $response_array['status'] = 'success';
        $response_array['message'] = 'Your Order has Processed. Please Note this pin <b style="background-color:green;">' . $pin . '</b> and send it to the admin with payment details.';
    } else {
        $response_array['status'] = 'error';
        $response_array['message'] = 'An error occurred. Please try again later.';
    }
    echo json_encode($response_array);
}

Can I place any check to JSON.parse if and only if my response is string?

Share Improve this question edited Nov 23, 2016 at 21:42 Ali Zia asked Nov 23, 2016 at 20:49 Ali ZiaAli Zia 3,8755 gold badges33 silver badges82 bronze badges 3
  • 1 When you set dataType: "json" it automatically parses the response as JSON. There's no need to do it manually. – castletheperson Commented Nov 23, 2016 at 20:57
  • You do echo json_encode($response_array); but are you sure you are doing before that a header('Content-Type:application/json')? – loretoparisi Commented Nov 23, 2016 at 21:51
  • Yes in my server.php, right below CORS, I am. 3rd line – Ali Zia Commented Nov 23, 2016 at 21:52
Add a ment  | 

4 Answers 4

Reset to default 3

Add this in your success handler.

data = typeof data === 'string' ? data : JSON.parse(data);

"Can I place any check to JSON.parse if and only if my response is string?" Yes, you can.

if (typeof (response) != 'object'){
response = JSON.parse(response);
}

You can use fairly simple javascript to do that:

if (typeof(data) == 'string') {
    data = JSON.parse(data);
}

If you are curious as to why it might not automatically parse your JSON, here are a couple mon reasons:

  • Invalid JSON (check with jsonlint.)
  • Not getting an application/json content type when expecting JSON (as set in the dataType parameter.

See also: jQuery won't parse my JSON from AJAX query

Remove the DATA_TYPE = 'json'; and try again:

function serverRequest(requestDATA, successCallback, errorCallback, hideIndicator, showAlert){
    var METHOD = "POST";
    var serverURL = 'http://istudy..pk/api/server.php'; //Path to Server.php
    //var serverURL = 'http://localhost/istudy/server.php'; //Path to Server.php
    var TIMEOUT = 20000;
    console.log(requestDATA);
    $$.ajax({
        url: serverURL,
        data: requestDATA,
        type: METHOD,
        timeout: TIMEOUT,
        success: function(data){
            try {
               if(typeof(data)==='string') data=JSON.parse(data);
            } catch(ex) { // bad json response
               console.error(ex);
            }
            successCallback(data, hideIndicator, showAlert);
        },
        error: function(a, b, c){
            errorCallback(a, b, c, hideIndicator, showAlert);
        }
    }); 
}

NOTE. This will not avoid the issue, but will let us to parse the response, while having a possibile bad response from the server i.e. a Content-Type that is not application/json. Some web server will accept both Content-Type:text/plain and Content-Type:application/json; headers, while returning in both cases a json formatted string rather than json object parsed by $.ajax (when finds the application/json as the Content-Type header value).

To achieve that, be sure in your php code to print out the right header

<?php

header('Content-Type: application/json`)

本文标签: javascriptHow can I check if my response is a string or JSON ObjectStack Overflow