您將需要使用AJAX
爲此,我需要他們在後端進行處理。假設你正在使用純JavaScript,而不是一個庫,你要沿着這些線路做一些事情:
//for cross browser support
var XMLHttpFactories =
[
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject("Msxml2.XMLHTTP")},
function() {return new ActiveXObject("Msxml3.XMLHTTP")},
function() {return new ActiveXObject("Microsoft.XMLHTTP")}
];
//find an xmlhttpfactory that will work
function createXMLHTTPObject()
{
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
};
//process post variables for your AJAX request
function parsePostData(postData)
{
var appendString = '?';
for(key in postData)
{
appendString += key + '=' + postData[key] + '&';
};
appendStrTrim = appendString.substring(0, appendString.length-1)
return appendStrTrim;
};
//this is where the magic happens
function sendRequest(url,callback,postData)
{
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
if (postData){
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
if (postData.passwd){
req.withCredentials = true;
}
}
req.onreadystatechange = function() {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
var errorCode = 'HTTP error: ' + req.status;
callback(errorCode);
}
var response = JSON.parse(req.response)
if (response.jquery){
console.log(req.getAllResponseHeaders());
}
if(response.data && response.data.modhash){
reddit.control.setModHash(response.data.modhash)
}
if(response.data && response.data.children && typeof callback =='function'){
callback(response.data.children);
}else if(response.data && typeof callback=='function'){
callback(response.data);
}else if(typeof callback== 'function'){
callback(response);
};
}
if (req.readyState == 4) return;
var postString = parsePostData(postData);
req.send(postString);
};
那麼,當你想改變PHP變量,你會打電話sendRequest()
像這樣:
`sendRequest('http://example.com/changeThosePHPVariables.php', function(){/*do this when done*/}, {amt: 'value', f: 'value'})
那麼你只需要使用changeThosePHPVariables.php
重新分配變量,你會發現它們是$_POST['amt']
和$_POST['f']
。
如果您使用像JQuery這樣的庫,您可以使用$ .ajax()來執行骯髒的工作,這一切都會變得更容易。
[javascript to php variable]可能重複(http://stackoverflow.com/questions/6084216/javascript-to-php-variable) – 2012-04-01 15:55:13
也許,但是這個問題沒有任何真正的答案... – 2012-04-01 15:58:27