简体   繁体   English

带有JS-Client的REST API

[英]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. 我打算创建一个小的api,该API可以执行一些php函数,但是只能由js实现。
I want to create a similar solution to the facebook sdk. 我想为Facebook SDK创建类似的解决方案。
So I created a php file named rest.php 所以我创建了一个名为rest.php的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. 和一个命名为conjs.js的js文件,现在我需要从conjs.js文件执行ajax请求,但是在尝试请求ajax请求时收到未定义的消息。
1) How should I build this? 1)我应该如何构建?
2) What am I doing wrong? 2)我在做什么错?

rest.php rest.php

<?php 

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

conjs.js --> included on the html page of client (similar to conjs.js- >包含在客户端的html页面中(类似于

connect.facebook.net/en_US/all.js off facebook) 在Facebook上关闭connect.facebook.net/en_US/all.js)

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- 客户端shtml HTML页面: -不在域上-

<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. 由于ajax的异步特性,您需要使用回调

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 . 在以下情况下,它位于ajax响应的成功块中,被认为很有趣

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. AFAIK $ _GET []区分大小写。 So either send lower case 'name=John' or read the correct $_GET['Name'] 因此,要么发送小写字母“ name = John”,要么读取正确的$ _GET ['Name']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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