简体   繁体   中英

REST API with JS-Client

I am intending to create a small api, that will do some php functions, but can be implemented by js only.
I want to create a similar solution to the facebook sdk.
So I created a php file named rest.php
and a js file nammed conjs.js now I need to perform an ajax request from the conjs.js file, but I get an undefined when trying to request an ajax request.
1) How should I build this?
2) What am I doing wrong?

rest.php

<?php 

echo "Hello from ".$_GET['name'];
?>

conjs.js --> included on the html page of client (similar to

connect.facebook.net/en_US/all.js off facebook)

function getDev(){
$.ajax({
    url: 'http://mydomain/rest.php',
    type: 'GET',
    data: 'Name=John', // or $('#myform').serializeArray()
    success: function(data) { return('Get completed '+data); }
});
}

Client smaple html page: -not on domain-

<html><head> <script src="http://mydomain/conjs.js"></script></head><body>
<script>
alert(getDev());
</script>
</body></html>

Thanks in advance :)

You need to use a callback due to ajax's asynchronous nature.

A callback is a function that is passed as an argument to another function which executes the callback at an interesting point. In the case below, it's in the success block of the ajax response which is considered as interesting .

Try this:

function getDev(callback){
$.ajax({
    url: 'http://mydomain.com/rest/rest.php',
    type: 'GET',
    data: 'Name=John', // or $('#myform').serializeArray()
    success: function(data) { 
        callback('Get completed '+data); 
    }
});
}

Later when calling:

<script type="text/javascript">
getDev(function (response) {
    alert(response);
});
</script>

AFAIK $_GET[] is case sensitive. So either send lower case 'name=John' or read the correct $_GET['Name']

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