카테고리 없음
[자바 스크립트] $ _POST에 전송하지 못했지만 $ _SESSION에 다른 메시지가 표시됨
필살기쓰세요
2021. 2. 19. 20:25
example.php가 요청을 처리하는 php 파일 인 경우 js 코드를 다음과 같이 변경해야합니다.
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
var jExample = JSON.stringify(array);
$.ajax("example.php", {
data:{'jExam':jExample},
type: 'POST',
dataType: 'json'
});
});
응답을 처리하려면 complete-Parameter를 추가해야합니다.
실수는 window.location.href
요청을 보내기 전에을 사용하여 페이지를 리디렉션하는 것 입니다. 따라서 요청이 전송되지 않고 PHP 파일이 필수 데이터가 아닌 AJAX를 통해 대신 직접 호출됩니다. 따라서 PHP 파일의 데이터가 누락되었습니다.
이 설정을 좀 더 쉽게 만들려고 시도 할 수 있으므로이를 단순화하는 데 도움이되는 몇 가지 사항이 있습니다. 이러한 작업 중 일부를 이미 수행했거나 수행하지 않았을 수 있으므로 이미 수행 한 작업은 무시하십시오.
- 1 단계 PHP 파일에 포함하는 구체적인 정의가있는 구성 파일 사용
- 하나의
data
필드를 전달하십시오.json_encode()
- json을 데이터 유형으로 보내지 마십시오. 필수 사항이 아닙니다. 먼저 문제를 해결 한 다음 필요한 경우 기본 전송 유형으로 설정하십시오.
success
반환을 쉽게 볼 수 있도록 함수를 사용하십시오.- 작업을 분리하는 기능 만들기
/config.php
모든 중요한 기본 설정을 추가하고 각 최상위 페이지에 추가하십시오.
session_start();
define('URL_BASE','http://www.example.com');
define('URL_AJAX',URL_BASE.'/ajax/dispatch.php');
define('FUNCTIONS',__DIR__.'/functions');
형태:
data
데이터 키 / 값 그룹을 보낼 하나 를 만드십시오 .
<button class="cart" data-instructions='<?php echo json_encode(array('name'=>'Whatever','price'=>'17.00','action'=>'add_to_cart')); ?>'>Add to Cart</button>
제공합니다 :
<button class="cart" data-instructions='{"name":"Whatever","price":"17.00","action":"add_to_cart"}'>Add to Cart</button>
Ajax :
그냥 정상적인 물건을 보내
$(document).ready(function(){
// Doing it this way allows for easier access to dynamic
// clickable content
$(this).on('click','.cart',function(e)){
e.preventDefault();
// Get just the one data field with all the data
var data = $(this).data('instructions');
$.ajax({
data: data,
type: 'POST',
// Use our defined constant for consistency
// Writes: http://www.example.com/ajax/dispatch.php
url: '<?php echo URL_AJAX; ?>',
success: function(response) {
// Check the console to make sure it's what we expected
console.log(response);
// Parse the return
var dataResp = JSON.parse(response);
// If there is a fail, show error
if(!dataResp.success)
alert('Error:'+dataResp.message);
}
});
});
});
/functions/addProduct.php
이상적으로 당신은 어떤 종류의 사용하고자하는 것 ID
또는 sku
키가 아닌 이름을
// You will want to pass a sku or id here as well
function addProduct($name,$price)
{
$_SESSION['cart'][$name]['name'] = $name;
$_SESSION['cart'][$name]['price'] = $price;
if(isset($_SESSION['cart'][$name]['qty']))
$_SESSION['cart'][$name]['qty'] += 1;
else
$_SESSION['cart'][$name]['qty'] = 1;
return $_SESSION['cart'][$name];
}
/ajax/dispatcher.php
디스패처는 AJAX 요청으로 만 작업을 다시 호출하기위한 것입니다. 반환 메커니즘의 특성으로 인해 확장하여 html을 반환하거나 여러 명령을 연속으로 실행하거나 하나만 실행할 수 있습니다.
# Add our config file so we have access to consistent prefs
# Remember that the config has session_start() in it, so no need to add that
require_once(realpath(__DIR__.'/../..').'/config.php');
# Set fail as default
$errors['message'] = 'Unknown error';
$errors['success'] = false;
# Since all this page does is receive ajax dispatches, action
# should always be required
if(!isset($_POST['action'])) {
$errors['message'] = 'Action is require. Invalid request.';
# Just stop
die(json_encode($errors));
}
# You can have a series of actions to dispatch here.
switch($_POST['action']) {
case('add_to_cart'):
# Include function and execute it
require_once(FUNCTIONS.'/addProduct.php');
# You can send back the data for confirmation or whatever...
$errors['data'] = addProduct($_POST['name'],$_POST['price']);
$errors['success'] = true;
$errors['message'] = 'Item added';
# Stop here unless you want more actions to run
die(json_encode($errors));
//You can add more instructions here as cases if you wanted to...
default:
die(json_encode($errors));
}
출처
https://stackoverflow.com/questions/39940144