GVKun编程网logo

如何通过ajax将数组发送到php?(ajax传数组)

15

本文将介绍如何通过ajax将数组发送到php?的详细情况,特别是关于ajax传数组的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于c#–通过AJAX

本文将介绍如何通过ajax将数组发送到php?的详细情况,特别是关于ajax传数组的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于c# – 通过AJAX将WIF发送到单独的域、javascript – 使用AJAX将数据发送到PHP、javascript – 如何使用通过AJAX发送到php的结帐令牌创建条带费用、javascript – 如何通过AJAX发送PHP数组?的知识。

本文目录一览:

如何通过ajax将数组发送到php?(ajax传数组)

如何通过ajax将数组发送到php?(ajax传数组)

我想发送一个用JavaScript构造的数组,其中包含多个select的选定值。有没有一种方法可以使用ajax将此数组发送到php脚本?

答案1

小编典典

您可以使用XML或JSON发回到服务器。您的javascript将必须构造该帖子,在XML的情况下,则需要您在javascript中创建它。JSON不仅轻巧,而且更易于在javascript中制作。签出JSON-
PHP来解析JSON。

您可能想看看在PHP中创建JSON数据

c# – 通过AJAX将WIF发送到单独的域

c# – 通过AJAX将WIF发送到单独的域

我们的网站运行在两个独立的域中,一个是安全API,另一个是前端网站.我们希望能够使用当前登录的用户凭据从网站向API执行ajax请求.

为此,我做了所有必要的CORS位,以便能够将我们的cookie传递给API,但是当API尝试处理cookie时,它无法解密它.我的理解是,这是因为领域不正确.

我尝试这样做时得到的错误如下:

InvalidOperationException: ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details). If you are using IIS 7.5,this Could be due to the loadUserProfile setting on the Application Pool being set to false.

如果我使用带有:1444域的cookie手动发出相同的请求,一切正常(所以我认为loadUserProfile的东西是红鲱鱼).

我认为问题是我不能将这个cookie重用于另一个领域.但如果是这种情况,我怎样才能在javascript中执行此委派?实际上甚至没有实际将用户重定向到STS以获得另一个领域的cookie吗?有没有更好的方法来处理这个JavaScript代理?

有用的支持数据:

我们的API端的WIF配置:

<modules runAllManagedModulesForAllRequests="true">
        <add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule,Microsoft.IdentityModel,Version=3.5.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
        <add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule,PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
    </modules>

<microsoft.identityModel>
    <service>
        <securityTokenHandlers>
            <add type="Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler,PublicKeyToken=31bf3856ad364e35">
                <sessionTokenRequirement lifetime="1:00" />
            </add>
        </securityTokenHandlers>
        <audienceUris>
            <add value="http://localhost:1444/" />
        </audienceUris>
        <federatedAuthentication>
            <wsFederation passiveRedirectEnabled="true" issuer="http://localhost:1339/account/sign-in" realm="http://localhost:1444/" requireHttps="false" persistentCookiesOnPassiveRedirects="false" />
            <cookieHandler requireSsl="false" path="/" name="TheCookieMonster" persistentSessionLifetime="60" />
        </federatedAuthentication>
        <applicationservice>
            <claimTyperequired>
                <!--This claim gets mapped to the User.Identity.Name-->
                <claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" optional="false" />
                <!--Some Other Custom claims-->
            </claimTyperequired>
        </applicationservice>
        <issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedissuerNameRegistry,PublicKeyToken=31bf3856ad364e35">
            <trustedissuers>
                <add thumbprint="a_thumbprint_key_for_our_cert" name="http://localhost:1339/" />
            </trustedissuers>
        </issuerNameRegistry>
    </service>
</microsoft.identityModel>

网站端的WIF配置:

(相同但有:1337)

<modules runAllManagedModulesForAllRequests="true">
        <add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule,PublicKeyToken=31bf3856ad364e35">
                <sessionTokenRequirement lifetime="1:00" />
            </add>
        </securityTokenHandlers>
        <audienceUris>
            <add value="http://localhost:1337/" />
        </audienceUris>
        <federatedAuthentication>
            <wsFederation passiveRedirectEnabled="true" issuer="http://localhost:1339/account/sign-in" realm="http://localhost:1337/" requireHttps="false" persistentCookiesOnPassiveRedirects="false" />
            <cookieHandler requireSsl="false" path="/" name="TheCookieMonster" persistentSessionLifetime="60" />
        </federatedAuthentication>
        <applicationservice>
            <claimTyperequired>
                <!--This claim gets mapped to the User.Identity.Name-->
                <claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" optional="false" />
                <!--Some Custom claims-->
            </claimTyperequired>
        </applicationservice>
        <issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedissuerNameRegistry,PublicKeyToken=31bf3856ad364e35">
            <trustedissuers>
                <add thumbprint="a_thumbprint_key_for_our_cert" name="http://localhost:1339/" />
            </trustedissuers>
        </issuerNameRegistry>
    </service>
</microsoft.identityModel>

网络标签的外观如下:

我认为这已被取消,因为JS已经检测到某种安全性废话.

>机器密钥在两个站点之间共享
>两者都在运行WIF 3.5

解决方法

我们确实设法通过升级到WIF 4.5来解决这个问题,WIF 4.5完美无缺地进行了特殊修改.我不太清楚3.5的根本原因是什么,但这已经为我解决了这个问题.如果有人想要它,我可以将这个工作的样本发布到GitHub

javascript – 使用AJAX将数据发送到PHP

javascript – 使用AJAX将数据发送到PHP

我在发布此问题之前已经搜索了我的问题,但未能找到解决方案.
我需要将一个json字符串发送到PHP文件但无法这样做,有人可以帮我解决下面的问题:我是PHP和jquery的新手并且正在努力,需要你的合作.

我有一个捕获文本文件数据的函数:

function updateVal() {
var node_list = document.getElementsByTagName('input');
var c = 0;
var fieldName = [];
var fieldText = []
var ID = [];
for (var i = 0; i < node_list.length; i++) {
    var node = node_list[i];
    if (node.getAttribute('type') == 'text') {
        fieldName[c] = node.name;
        fieldText[c] = node.value;
        ID[c] = node.id;
        c++;
    }
}
var postData = {
    fieldName: fieldName,
    fieldText: fieldText,
    ID: ID
};
 var dataString = JSON.stringify(postData);


console.log(JSON.stringify(postData));
$.ajax({
        type: "POST",
        dataType: "json",
        url: "update.PHP",
        data: {myData:postData}
        })

//return JSON.stringify(postData);
}

我的update.PHP是这样的:

<?PHP
$json = $_POST['json'];
$result = json_decode($json);

echo $result;
echo $_POST['myData']);?>

加载时:我收到以下错误:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

而且,我不确定是否将数据发送到PHP.
专家们可以证实.

解决方法:

500(内部服务器错误)意味着服务器端出现了问题.因此,请查看apache错误日志以获取更多详细信息

你可能会在这里找到apache log / var / log / apache2 /

javascript – 如何使用通过AJAX发送到php的结帐令牌创建条带费用

javascript – 如何使用通过AJAX发送到php的结帐令牌创建条带费用

我试图用自定义按钮使用Stripe的新结帐功能,通过 AJAX POST发送令牌到PHP文件,然后执行费用.不幸的是,我从POST变量中检索到令牌有一些麻烦.我希望这里的某个人能够告诉我我过于简单,如果有一个更简单的方法来做到这一点.

在客户端,我有5个按钮,不同的可能“捐款”.这是迄今为止写的js(不包括html):

$(function() {

  var donationAmt = '';
  var handler = StripeCheckout.configure({
    key: 'pk_test_3plF76arhkygGMgwCEerThpa',image: '/square-image.png',token: function(token,args) {
      // Use the token to create the charge with a server-side script.
      // You can access the token ID with `token.id`
      console.log(token)
      var chargeData = {
        donationAmt: donationAmt,token: token
      }
      $.ajax({
          url: '/link/to/PHP/stripeDonate.PHP',type: 'post',data: {chargeData: chargeData},success: function(data) {
            if (data == 'success') {
                console.log("Card successfully charged!")
            }
            else {
                console.log("Success Error!")
            }

          },error: function(data) {
                console.log("Ajax Error!");
                console.log(data);
          }
        }); // end ajax call
    }
  });

  $('.donate-button').bind('click',function(e) {
    donationAmt = $(this).html().substring(1) + '00';
    donationAmt = parseInt(donationAmt); // Grabs the donation amount in the html of the button and store it in a variable
    // Open Checkout with further options
    handler.open({
      name: 'Company Name',description: 'A donation',amount: donationAmt
    });
    e.preventDefault();
  });
});

这是我正在处理AJAX POST调用的PHP:

<?PHP

require_once('Stripe.PHP');

// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://manage.stripe.com/account
Stripe::setApiKey("sk_test_APIKEYREDACTED");

// Get the credit card details submitted by the form
$token = json_decode($_POST['chargeData']);
$tokenid = $token['id'];

// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = Stripe_Charge::create(array(
  "amount" => 2000,// amount in cents,again
  "currency" => "usd","card" => $tokenid,"description" => "payinguser@example.com")
);
echo 'success';
} catch(Stripe_CardError $e) {
  // The card has been declined
    echo $tokenid;
}

?>

PHP错误日志中指出的代码的直接结果是令牌的POST变量不能被“读取”.令牌正在被创建(我正在控制台上看到它),但是当我通过AJAX发送时它消失了.

每个人都一直在说条纹是非常容易实现的,所以我真的觉得我在这里缺少一些东西.有人能够散发光吗?

谢谢!

解决方法

所以经过10个小时的休息和一个更清晰的头,我已经决定以稍微不同的方式解决这个问题.这是任何其他人绊倒我相同的问题,并希望能够像条纹/ ajax / PHP教程一样很好地工作.原来我一直在想POST数据都错了.即使使用AJAX,您也需要一个键和值对来发送任何类型的POST数据.我已经重新编码了我的这个部分:
var handler = StripeCheckout.configure({
    key: 'PUBLISHABLEKEY',args) {
      // Use the token to create the charge with a server-side script.
      // You can access the token ID with `token.id`
      console.log(token)
      $.ajax({
          url: 'link/to/PHP/stripeDonate.PHP',data: {tokenid: token.id,email: token.email,donationAmt: donationAmt},success: function(data) {
            if (data == 'success') {
                console.log("Card successfully charged!");
            }
            else {
                console.log("Success Error!");
            }

          },error: function(data) {
            console.log("Ajax Error!");
            console.log(data);
          }
        }); // end ajax call
    }
  });

请注意,一个主要更改是ajax方法的数据属性.控制台记录令牌对象显示整个JSON令牌对象,您可以使用它来提取ID(您的服务器需要发送到条带以收取费用)以及电子邮件(用于记录目的).由于我有一个可变的捐赠金额,我已经把它作为第三个关键.

现在在你的PHP中,为了获取这些POST变量并把它们放入PHP变量中,你可以使用它们各自的键来获取它们:

$tokenid = $_POST['tokenid'];
$donation = $_POST['donationAmt'];
$email = $_POST['email'];

然后一切都应该是自我解释的(以下几乎是与条纹PHP教程完全相同的例子).

无论如何,希望这有助于一个人在那里.祝你好运!

javascript – 如何通过AJAX发送PHP数组?

javascript – 如何通过AJAX发送PHP数组?

在我的注册页面上,人们可以通过填写一些输入广告复选框来注册我的网站.它基本上是一个将数据发送到带有ajax的 PHP页面的表单,然后将其放入数据库中.

例如,javascript从表单中获取值

var w = _("website").value;
var bio = _("bio").value;

然后像这样发送ajax.send(“w =”w“& bio =”bio);这是应该的,但我想添加一些东西.

现在我有一些复选框,我希望在一个数组中通过ajax发布在一个变量中.所以在我的表单中我有这段PHP:

$licensessql = MysqLi_query($db_conx,"SELECT * FROM licenses");
while($licenserecord = MysqLi_fetch_assoc($licensessql)) {
echo '<input type="checkBox" value="'.$licenserecord["license"].'" name="licenses[]" id="'.$licenserecord["license"].'"><label for="'.$licenserecord["license"].'">'.$licenserecord["license"].'</label><br>';
}

使用纯PHP,这将工作,并将复选框中的所有值放在数组license []中,但我不知道如何使用ajax实现此目的.如果我有5个复选框,我希望javascript var具有例如值’value1,value2,value3’并将其发布到PHP.

谢谢!

解决方法

首先,我建议使用其他答案中发布的表单序列化.

要回答你的实际问题:“如果我有5个复选框,value3’并将其发布到PHP.”

这是一个完整的工作示例(使用3个复选框),它将生成一个javascript变量,您可以使用该变量传递给您的AJAX post方法以供PHP处理.

JSfiddle:https://jsfiddle.net/o5q04vf0/

代码片段:

$(document).ready(function() {
  $('#btnTest').click(function() {
    var checkBoxValues = $("[name=licenses\\[\\]]").map(function() {
      if ($(this).is(':checked')) {
        return this.value;
      }
    }).get().join();

    alert(checkBoxValues);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkBox" value="0" name="licenses[]" />
<input type="checkBox" value="1" name="licenses[]" />
<input type="checkBox" value="2" name="licenses[]" />
<button id="btnTest">Submit</button>

这将帮助您指导正确的方向,但请考虑通过AJAX传递数据,就像这里建议的其他成员一样.

关于如何通过ajax将数组发送到php?ajax传数组的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于c# – 通过AJAX将WIF发送到单独的域、javascript – 使用AJAX将数据发送到PHP、javascript – 如何使用通过AJAX发送到php的结帐令牌创建条带费用、javascript – 如何通过AJAX发送PHP数组?等相关内容,可以在本站寻找。

本文标签: