Кажется, что это особый способ структурировать переменную, особенно если учесть, что вам нужно дополнительно обработать ее, чтобы получить нужный идентификатор.Вы могли бы сделать это проще, как это?Преимущество этого состоит в том, что вы можете отправлять много параметров без необходимости изменять внутреннюю часть функции - просто добавьте больше параметров / значений к объекту переменной theVar
.
html
<button type='button' onclick='myFunction( { postId:<?php echo $post['postId']; ?> } );'>Click me</button>
javascript
<script>
const myFunction=function( theVar ) {
var xhr=new XMLHttpRequest();
var url = 'includes/file.php';
var query=[];
Object.keys( theVar ).map( function( key ){
query.push( key+'='+theVar[key] )
} );
url+='?'+query.join('&');
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert('Success!');
}
};
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
}
</script>
Тем не менее, после незначительного редактирования ниже работало хорошо для меня только сейчас.Код PHP, который я использовал ниже, тоже ...
const myFunction=function( theVar ) {
var xhr=new XMLHttpRequest();
var url = 'includes/file.php';
if (theVar.includes('postId')) {
url = url + '?postId=' + theVar.substr(theVar.length - 1);
} else if (theVar.includes('userId')) {
url = url + '?userId=' + theVar.substr(theVar.length -1);
} else if (theVar.includes('commentId')) {
url = url + '?commentId=' + theVar.substr(theVar.length -1);
}
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert('Success!');
}
};
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
}
Цель теста PHP
<?php
echo json_encode( $_REQUEST );
?>
Ответ
{"postId":"4"}
Вы можете изменить PHP, чтобы сделатьэто немного более безопасно, используя подготовленные операторы.
<?php
if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && !empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest" ) {
require 'connection.php';
$postId = filter_input( INPUT_GET, 'postId', FILTER_SANITIZE_NUMBER_INT );
$commentId = filter_input( INPUT_GET, 'commentId', FILTER_SANITIZE_NUMBER_INT );
$userId = filter_input( INPUT_GET, 'userId', FILTER_SANITIZE_NUMBER_INT );
$sql=false;
if( $postId ){
$sql='update `posts` set `postVotes` = `postVotes` + 1 where postId=?;';
$id=$postId;
}
/* assumed similar table called comments */
if( $commentId ){
$sql='update `comments` set `commentVote` = `commentVote` + 1 where `commentId`=?;';
$id=$commentId;
}
/* etc - users too?? */
if( $userId ){
$sql='.... etc etc ';
$id=$userId;
}
if( $sql ){
$stmt=$link->prepare( $sql );
$stmt->bind_param('i', $id );
$res=$stmt->execute();
}
} else {
exit( header( 'HTTP/1.1 403 Forbidden', true, 403 ) );
}
?>
Полный, одна страница, демо
<?php
if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && !empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest" ) {
ob_clean();
$postId = filter_input( INPUT_GET, 'postId', FILTER_SANITIZE_NUMBER_INT );
$commentId = filter_input( INPUT_GET, 'commentId', FILTER_SANITIZE_NUMBER_INT );
$userId = filter_input( INPUT_GET, 'userId', FILTER_SANITIZE_NUMBER_INT );
/*
here you would con
*/
$output=array(
'post' => $postId,
'comment' => $commentId,
'user' => $userId
);
echo json_encode( $output );
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>ajax</title>
<style>
body{display:flex;flex-direction:column;padding:1rem;margin:0;box-sizing:border-box;font-family:cursive;font-size:1rem;}
div{display:flex;flex-direction:row;justify-content:center;align-content:space-between;align-items:center;flex:1;order:1;width:100%;}
output{display:flex;flex:2;order:2;width:100%;justify-content:center;margin:1rem auto;}
button{padding:1rem;margin:auto}
</style>
<script>
const callback=function(r){
if( r ){
document.querySelector( 'output' ).innerHTML=r;
}
};
const myFunction=function(theVar){
var xhr=new XMLHttpRequest();
var url = location.href;
if (theVar.includes('postId')) {
url = url + '?postId=' + theVar.substr(theVar.length - 1);
} else if (theVar.includes('userId')) {
url = url + '?userId=' + theVar.substr(theVar.length -1);
} else if (theVar.includes('commentId')) {
url = url + '?commentId=' + theVar.substr(theVar.length -1);
}
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200 ) {
callback( this.response )
}
};
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
};
const myOtherFunction=function( theVar ) {
var xhr=new XMLHttpRequest();
var url = location.href;
var query=[];
Object.keys( theVar ).map( function( key ){
query.push( key+'='+theVar[key] )
} );
url+='?'+query.join('&');
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200 ) {
callback( this.response )
}
};
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
}
</script>
</head>
<body>
<div>
<button type='button' onclick='myOtherFunction( { postId:808 } );'>Click me [POSTID]</button>
<button type='button' onclick='myOtherFunction( { commentId:909 } );'>Click me [COMMENTID]</button>
<button type='button' onclick='myOtherFunction( { userId:303 } );'>Click me [USERID]</button>
<button type='button' onclick='myOtherFunction( { postId:808,commentId:909,userId:303 } );'>Click me [ALL]</button>
</div>
<div>
<button type='button' onclick='myFunction( "postId808" );'>Click me [STRING - POSTID]</button>
<button type='button' onclick='myFunction( "commentId909" );'>Click me [STRING - COMMENTID]</button>
<button type='button' onclick='myFunction( "userId303" );'>Click me [STRING - USERID]</button>
</div>
<output></output>
</body>
</html>