Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...