简体   繁体   中英

Returning JSON from PHP, convert JSON to javascript array, return array from AJAX call

I am working on a project that uses a function I called AjaxRequest which handles all AJAX requests I make. I have no problems in making the request however getting the request back is the issue and placing it where I want it on my page is becoming stressful.

HTML BIT

<body onLoad="calling();">
<div id="status">Status: </div>
</body>

JAVASCRIPT BIT

function calling() {
    var answer = ajaxRequest("testing", "test.php", "test=test");

    document.getElementById("status").innerHTML += answer[1];
    document.getElementById("status").innerHTML += " " + answer[3];
}

function ajaxRequest(app, location, credentials) {  
var extras = ""; 
if(credentials === "" || credentials) { 
        extras = "&" + credentials; 
    }

    var ajax = ajaxObj("POST", location);
    ajax.onreadystatechange = function() {
        if(ajaxReturn(ajax) == true) {
            var obj = JSON.parse(ajax.responseText);
            var arrayObj = [];
            for(var i in obj) { arrayObj.push([i, obj[i]]); }
            return arrayObj;
        }
    }
    ajax.send("app=" + app + extras); 
}

there are two other functions running: ajaxObj and ajaxReturn but I excluded those because they is not the problem. Furthermore, I am trying to make ajaxRequest an efficient function that could be used by more than one application without having to rewrite all the code in more than one location. All error handling acquires before the actual use of ajaxRequest.

PHP BIT

<?php
if($_POST['app'] == "testing") {
    $hey = array('success' => 1, 'message' => 'Successful');
    echo json_encode($hey);
    exit();
}
?>

I'm using calling as a javascript function that does all error handling, this is just basic for the whole of my project however I try to get the JSON from php and convert it to array and the issue is returning the array into calling. I try to display the information on the page yet nothing works.

I am not looking to use any JQuery for my project so I would like to exclude the use of it for this piece of code.

If you want, you could set the header before sending back the json.

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

Usually you don't need it, but it will tell your javascript that it's json, and the array will be transform in a javascript object. It work with Jquery, but I assume it'll work without too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM