Jump to content
  • 0

вызов функции PHP из JS


NickAssa
 Share

Question

Удачного дня!

Можно ли вызвать ф-цию написанную на PHP из JS.

Задача в следующем

Нужно изменить значение в БД.

Как работать с MySQL посредсвом PHP мне известно. JS в силу того, что работает на стороне клиента, этого делать не умеет (или я ошибаюсь?). Поэтому и хотелось вызвать ф-цию PHP.

<html>
...
<body>
<script language="JavaScript">
function doClickSave()
{
.....
Save_data(var);
....
}
</script>

<FORM>
...
...
<?
function Save_data($par1)
{
$cnctDB = mysql_connect(...);
...
}
?>
</FORM>
</body>
</html>

Link to comment
Share on other sites

11 answers to this question

Recommended Posts

  • 0

либо совсем неприличным способом - открываем маленький попап примерно 50*50, в котором будет как раз осуществлться отправка запроса и прописан онлоад=таймаут примерно 0,5 сек: окно.клоуз

Link to comment
Share on other sites

  • 0
...скрипт отличается повышенной кроссбраузерностью...

Оффтоп, но очень уж хочется узнать - чем измеряется кроссбраузерность и как ее можно повысить или, не дай бог, понизить? :lol:

Link to comment
Share on other sites

  • 0

Вот и я)).... сечас-сечас...

jsData.php:

<?php

// —————————————————— //
// Script name: jsData //
// Version: 0.5beta //
// //
// Autor: Maslakov Alexander //
// Email: jmas.ukraine@gmail.com //
// Country: Ukraine //
// Used scripts: //
// - FastJSON (site: http://www.devpro.it/) //
// - JSONscriptRequest (autor: Jason Levitt) //
// - Sajax (site: http://www.modernmethod.com/sajax/) //
// —————————————————— //



// <FastJSON:class> ////////////////////////////////////////////

class FastJSON {

function convert($params, $result = null){
switch(gettype($params)){
case 'array':
$tmp = array();
foreach($params as $key => $value) {
if(($value = FastJSON::encode($value)) !== '')
array_push($tmp, FastJSON::encode(strval($key)).':'.$value);
};
$result = '{'.implode(',', $tmp).'}';
break;
case 'boolean':
$result = $params ? 'true' : 'false';
break;
case 'double':
case 'float':
case 'integer':
$result = $result !== null ? strftime('%Y-%m-%dT%H:%M:%S', $params) : strval($params);
break;
case 'NULL':
$result = 'null';
break;
case 'string':
$i = create_function('&$e, $p, $l', 'return intval(substr($e, $p, $l));');
if(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $params))
$result = mktime($i($params, 11, 2), $i($params, 14, 2), $i($params, 17, 2), $i($params, 5, 2), $i($params, 9, 2), $i($params, 0, 4));
break;
case 'object':
$tmp = array();
if(is_object($result)) {
foreach($params as $key => $value)
$result->$key = $value;
} else {
$result = get_object_vars($params);
foreach($result as $key => $value) {
if(($value = FastJSON::encode($value)) !== '')
array_push($tmp, FastJSON::encode($key).':'.$value);
};
$result = '{'.implode(',', $tmp).'}';
}
break;
}
return $result;
}

function decode($encode, $stdClass = false){
$pos = 0;
$slen = is_string($encode) ? strlen($encode) : null;
if($slen !== null) {
$error = error_reporting(0);
set_error_handler(array('FastJSON', '__exit'));
$result = FastJSON::__decode($encode, $pos, $slen, $stdClass);
error_reporting($error);
restore_error_handler();
}
else
$result = null;
return $result;
}

function encode($decode){
$result = '';
switch(gettype($decode)){
case 'array':
if(!count($decode) || array_keys($decode) === range(0, count($decode) - 1)) {
$keys = array();
foreach($decode as $value) {
if(($value = FastJSON::encode($value)) !== '')
array_push($keys, $value);
}
$result = '['.implode(',', $keys).']';
}
else
$result = FastJSON::convert($decode);
break;
case 'string':
$replacement = FastJSON::__getStaticReplacement();
$result = '"'.str_replace($replacement['find'], $replacement['replace'], $decode).'"';
break;
default:
if(!is_callable($decode))
$result = FastJSON::convert($decode);
break;
}
return $result;
}

function __getStaticReplacement(){
static $replacement = array('find'=>array(), 'replace'=>array());
if($replacement['find'] == array()) {
foreach(array_merge(range(0, 7), array(11), range(14, 31)) as $v) {
$replacement['find'][] = chr($v);
$replacement['replace'][] = "u00".sprintf("%02x", $v);
}
$replacement['find'] = array_merge(array(chr(0x5c), chr(0x2F), chr(0x22), chr(0x0d), chr(0x0c), chr(0x0a), chr(0x09), chr(0x08)), $replacement['find']);
$replacement['replace'] = array_merge(array('', '/', '"', 'r', 'f', 'n', 't', 'b'), $replacement['replace']);
}
return $replacement;
}
function __decode(&$encode, &$pos, &$slen, &$stdClass){
switch($encode{$pos}) {
case 't':
$result = true;
$pos += 4;
break;
case 'f':
$result = false;
$pos += 5;
break;
case 'n':
$result = null;
$pos += 4;
break;
case '[':
$result = array();
++$pos;
while($encode{$pos} !== ']') {
array_push($result, FastJSON::__decode($encode, $pos, $slen, $stdClass));
if($encode{$pos} === ',')
++$pos;
}
++$pos;
break;
case '{':
$result = $stdClass ? new stdClass : array();
++$pos;
while($encode{$pos} !== '}') {
$tmp = FastJSON::__decodeString($encode, $pos);
++$pos;
if($stdClass)
$result->$tmp = FastJSON::__decode($encode, $pos, $slen, $stdClass);
else
$result[$tmp] = FastJSON::__decode($encode, $pos, $slen, $stdClass);
if($encode{$pos} === ',')
++$pos;
}
++$pos;
break;
case '"':
switch($encode{++$pos}) {
case '"':
$result = "";
break;
default:
$result = FastJSON::__decodeString($encode, $pos);
break;
}
++$pos;
break;
default:
$tmp = '';
preg_replace('/^(-)?([0-9]+)(.[0-9]+)?([eE]+[0-9]+)?/e', '$tmp = "1234"', substr($encode, $pos));
if($tmp !== '') {
$pos += strlen($tmp);
$nint = intval($tmp);
$nfloat = floatval($tmp);
$result = $nfloat == $nint ? $nint : $nfloat;
}
break;
}
return $result;
}
function __decodeString(&$encode, &$pos) {
$replacement = FastJSON::__getStaticReplacement();
$endString = FastJSON::__endString($encode, $pos, $pos);
$result = str_replace($replacement['replace'], $replacement['find'], substr($encode, $pos, $endString));
$pos += $endString;
return $result;
}
function __endString(&$encode, $position, &$pos) {
do {
$position = strpos($encode, '"', $position + 1);
}while($position !== false && FastJSON::__slashedChar($encode, $position - 1));
if($position === false)
trigger_error('', E_USER_WARNING);
return $position - $pos;
}
function __exit($str, $a, $b) {
exit($a.'FATAL: FastJSON decode method failure [malicious or incorrect JSON string]');
}
function __slashedChar(&$encode, $position) {
$pos = 0;
while($encode{$position--} === '')
$pos++;
return $pos % 2;
}

}

// </FastJSON:class> ////////////////////////////////////////////

// **********************************************************************

// <jsdata_intercept_request> ////////////////////////////////////////////

function jsdata_intercept_request(){

if(!empty($_GET['rf'])){ header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");

if(function_exists($_GET['rf']))
$func_name = $_GET['rf'];
else
exit;

if(!empty($_GET['rargs']))
foreach($_GET['rargs'] as $k=>$v) $args[]=rawurldecode($v);
else
$args = array();

$json_data = FastJSON::encode(call_user_func_array($func_name, $args));

print $_GET['rf_cb'].'('.$json_data.');';

exit;
}

}

// </jsdata_intercept_request> ////////////////////////////////////////////

// **********************************************************************

// <jsdata_processing_functions> ////////////////////////////////////////////

$jsdata_processing_functions_js = '';

function jsdata_processing_functions(){
global $jsdata_processing_functions_js;

$args = func_get_args();

for($i=0; $i<count($args); $i++){

$jsdata_processing_functions_js .= '
function x_'.$args[$i].'(){
jsdata_do_call("'.$args[$i].'", x_'.$args[$i].'.arguments);
}

';

}

}

// </jsdata_processing_functions> ////////////////////////////////////////////

// **********************************************************************

// <jsdata_javascript> ////////////////////////////////////////////

function jsdata_javascript(){
global $jsdata_processing_functions_js;
?>

// BEGIN: jsData ////////////////////////////////////////////

function JSONscriptRequest(fullUrl) {
this.fullUrl = fullUrl;
this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
this.headLoc = document.getElementsByTagName("head").item(0);
this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

JSONscriptRequest.scriptCounter = 1;

JSONscriptRequest.prototype.buildScriptTag = function () {
this.scriptObj = document.createElement("script");
this.scriptObj.setAttribute("type", "text/javascript");
// this.scriptObj.setAttribute("charset", "utf-8");
this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
this.scriptObj.setAttribute("id", this.scriptId);
}

JSONscriptRequest.prototype.removeScriptTag = function () {
this.headLoc.removeChild(this.scriptObj);
}

JSONscriptRequest.prototype.addScriptTag = function () {
this.headLoc.appendChild(this.scriptObj);
}

function jsdata_do_call(func_name, args){
var request = '<?=$_SERVER["REQUEST_URI"]?>';
if (request.indexOf("?") == -1)
request += "?rf=" + escape(func_name);
else
request += "&rf=" + escape(func_name);
request += "&rsrnd=" + new Date().getTime();
for (i = 0; i < args.length-1; i++)
request += "&rargs[]=" + escape(args[i]);
request += "&rf_cb=" + args[args.length-1];

//document.write(request);

aObj = new JSONscriptRequest(request);
aObj.buildScriptTag();
aObj.addScriptTag();
}
<?=$jsdata_processing_functions_js?>
// END: jsData ////////////////////////////////////////////

<?

}

// </jsdata_javascript> ////////////////////////////////////////////

// **********************************************************************

?>

Тестовый пример (test.php):

<?php

require_once('jsData.php');


// Объявление php-функций для запроса

function get_data($a,$b,$c){
return array($a, $b, $c, 'abc','абв');
}

// Конфигурация jsData

jsdata_processing_functions('get_data');
jsdata_intercept_request();

?>

<html>
<head>
<title>test</title>
</head>
<body>

<script>

<?
// Вставка JavaScript-обработчика запросов
jsdata_javascript();

?>

function get_data_cb(ret_data){
document.getElementById('dat').innerHTML = unescape(ret_data[2]);
}

function get_data_js(){
//alert('send to next');
x_get_data('one_arg','two_arg 111','Ч?т непонятное!','get_data_cb');
}

</script>

<div id='dat'>Content</div>

</body>
</html>

Ну В общем разберайтесь))) если что -- спрашивайте. Просто работы уйма(((

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy