让AJAX从JavaScript到PHP传递字符串变量字符串、变量、AJAX、JavaScript

2023-09-10 15:53:07 作者:愿负天下人不负你

这是我现在使用的JavaScript

This is the javascript I am using now

<script>
    $( document ).ready(function() {
        var namer = sessionStorage.getItem("namer");
        $.ajax({
            type: "POST",
            url: "Antibiotics2.php",
            data: { 'name': namer }
        }).done(function( msg ) {
            alert( "Data Saved: " + msg );
        });
    });
</script>

这是PHP:

and this is the php:

<?php echo $_POST['name']; ?>            

这将引发错误,并表示,该指数'名'无法找到。

It throws an error and says that the index 'name' can't be found.

推荐答案

嗯,我复制你的设置和每个我能够找回在$ _ POST设置变量的时间。我也避免了修改名字,你说,该会议是在正确类似的问题抓获。

Well I have replicated your set up and each time I am able to retrieve the variable set within $_POST. I have also avoided amending names as you stated that the session is being correctly captured in a similar question.

我能够通过设置纳默变量未定义或试图通过检索值不是present重现错误。

I was able to reproduce the error by setting the namer variable to undefined or by trying to retrieve a value which was not present.

由于我能够只要发送变量纳默,因为它被设置,那么你就必须做一些事情。

Since I was able to send the variable namer as long as it is set then you will have to do a couple of things.

检查纳默变量设置,或者客户端和服务器端。这是在JavaScript,你将测试如果变量是不是不确定的,或者你会在PHP检查$ _ POST ['纳默']设置。

Check if the namer variable is set, perhaps client and server side. That is in javascript you would test if the variable is not undefined or in php you would check if $_POST['namer'] is set.

您的会话可能会过期,因此您要检索的值ofcourse已经不存在,创建会话,当你宣称这可能是取决于哪些库,你正在使用或设置

Your session may expire and therefore you are trying to retrieve a value that ofcourse is no longer there, this could be dependent upon which library you are using or settings you declared when creating the session

在这两种情况下,你会遇到同样的错误,并做一些逻辑分析,你就会避免这个错误。

In both instances you will experience the same error and by doing some logic you will avoid this error.

服务器端检查 - PHP的:

Server side check - PHP:

if(isset($_POST['namer'])){
    echo $_POST['namer'];
}else{
    echo "session capture unsuccessful";
}

客户端检查 - JavaScript的:

Client side check - Javascript:

var namer = sessionStorage.getItem("namer");

if (typeof namer === "undefined")
    console.log("your session is not set");
} else{
    // you could place your ajax request here
    // or you could set the namer variable to a default value
}

请尽可能在本地开发Web应用程序,因为它是更容易调试,并作为最后一点,可能更容易使用的console.log(yourError)用于调试的目的,而不是警报(yourError)。

Please if possible develop your web applications locally as it is easier to debug and as a final note it may be easier to use console.log(yourError) for debugging purposes rather than alert(yourError).

 
精彩推荐