猿问

Javascript:从PHP(使用jQuery)进行Ajax调用

它应该如何工作:我向color.php发送一个参数。我为此做了一个变量(语言)。然后返回带有3个参数的json对象:颜色,背景颜色和文本。


color.php


<?php

$result = Array("color"=>"", "bgcolor" => "", "text" => "");

$result["color"] = "rgb(".rand(0,255).",".rand(0,255).",".rand(0,255).")";

$result["bgcolor"] = "rgb(".rand(0,255).",".rand(0,255).",".rand(0,255).")";

switch($_GET["nyelv"]) {

    case "magyar":

        $result["text"] = "Hungarian text";

        break;

    case "angol":

        $result["text"] = "English tetx";

        break;

}

echo json_encode($result);

?>

我的JavaScript函数:


$("#modosits").click(function(){

    var language =$("#nyelv").val();

    $.ajax({

      "url": "color.php",

      "type": "get",

      "data": language,

      "dataType": "json",

      "success": function(data) {

        $("#magyar").css("color", data.color);

        $("#magyar").css("background-color", data.bgcolor);

        $("#magyar").text(data.text);

      }

    })

});


慕标琳琳
浏览 135回答 3
3回答

元芳怎么了

您不是将数据对象发送给PHP,而是将字符串语言发送给PHP。在您使用的PHP中$_GET["nyelv"],将该属性发送到您的数据中,例如data: { nyelv: language}。&nbsp;$("#modosits").click(function(){&nbsp; &nbsp; var language =$("#nyelv").val();&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; "url": "color.php",&nbsp; &nbsp; &nbsp; "type": "get",&nbsp; &nbsp; &nbsp; "data": { nyelv: language },&nbsp; &nbsp; &nbsp; "dataType": "json",&nbsp; &nbsp; &nbsp; "success": function(data) {&nbsp; &nbsp; &nbsp; &nbsp; $("#magyar").css("color", data.color);&nbsp; &nbsp; &nbsp; &nbsp; $("#magyar").css("background-color", data.bgcolor);&nbsp; &nbsp; &nbsp; &nbsp; $("#magyar").text(data.text);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })});

HUWWW

您可以使用它:$("#modosits").click(function(){var myColor = $("#my_color").val();var mybgColor= $("#mybgColor").val();var mytext= $("#mytext").val();$.ajax({&nbsp; "url": "color.php",&nbsp; "type": "get",&nbsp; "data": {&nbsp; &nbsp; &nbsp;color: myColor,&nbsp; &nbsp; &nbsp;bgcolor: mybgColor,&nbsp; &nbsp; &nbsp;text: mytext&nbsp; },&nbsp; "dataType": "json",&nbsp; "success": function(data) {&nbsp; &nbsp; $("#magyar").css("color", data.color);&nbsp; &nbsp; $("#magyar").css("background-color", data.bgcolor);&nbsp; &nbsp; $("#magyar").text(data.text);&nbsp; }})或者您可以在客户端使用JSON.stringify(language)并在服务器端使用json_decode(language)

慕田峪7331174

假设您正在发送正确的参数并进行正确的处理,并且还发送回了正确的数据(在您的代码上看起来一切都很好)...缺少的只是一个翻译者,可以说!试试这段代码:"success": function(resp) {&nbsp; &nbsp; var data = JSON.parse(resp) ;&nbsp; &nbsp; $("#magyar").css("color", data.color);&nbsp; &nbsp; $("#magyar").css("background-color", data.bgcolor);&nbsp; &nbsp; $("#magyar").text(data.text);&nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答