Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

php - jQuery Ajax on Different Port

My php file located at port 80 (default port) while my ajax call are on port 8080.

My index.html on port 8080

$(document).ready(function(){
$.get("userCheck.php", 
        {"username" : "lazy", "favcolor" : "FFFFFF" },          
        function(data){ alert("Data Loaded: " + data);
});

My PHP

$user = $_GET["username"];
if($user == "lazy")
    echo "SUCESS";
else
    echo "FAIL";

I have googled abit, JSONP came out mostly. Any idea how to convert it to JSONP?

Any way to make it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could try creating a full URL with a port number (http://myserver:[port]/userCheck.php), but it won't work. (Same origin policy)

Performing a query on a different port is not something you should use JSONP for, because any good JSONP framework would block that (or at least it should). It's not the primary goal of JSONP to allow these things, it's only a side-effect from the implementation.

But you can create a "facade" PHP script on the same port as index.html, which then performs the query to the different URL and returns the value. This way the browser does not know about the real URL.

index.html (8080) <--> myAjaxFacade.php (8080) <--> userCheck.php (80)

To do this you could use the http-post-fields function, for example.

Example:

$(document).ready(function(){
$.get("myAjaxFacade.php", 
    {"username" : "lazy", "favcolor" : "FFFFFF", 
     "realUrl": "http://serverwithdifferent:port/userCheck.php" },          
    function(data){ alert("Data Loaded: " + data);
});

In myAjaxFacade.php then forward all other POST data to $_POST['realUrl'] and return the response from that URL.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...