duanluanlang8501 2013-08-13 01:50
浏览 34
已采纳

使用AJAX将参数发送到php控制器的最佳方法

I want to sent 2 parameters from the client ( jquery ) side to server side ( php-codeigniter ). The parameters are id ( an integer ) and text ( a string ). I tried:

window.location.href="AjaxUpdate/sendMessage/"+id+"/"+text;

which has worked for me in the past using only the id, but because the text string can have spaces I can get:

http://localhost/b1/mycontroller/myfunction/3/gdfgdgd%20 %20 gd 

which gives:

An Error Was Encountered
The URI you submitted has disallowed characters.

What is the best way to prepare and transmit a string to the server side using jquery? I assume ajax will be used in some way

  • 写回答

1条回答 默认 最新

  • doushi6864 2013-08-13 01:54
    关注

    You can use the jQuery .ajax() function to POST data (JSON) to your PHP script, like this:

    var postData = {
        "param1" : some_value1,
        "param2" : some_value2
    };
    
    console.log(postData);
    
    $.ajax({
        type: "POST",
        url: "test.php",
        data: postData, 
        success: function(){
            alert(param1 + ' ' + param2);
            window.open("test.php"); 
        }
    });
    

    UPDATE:

    PHP sample that I Googled and found; it doesn't seem to do much, but unfortunately I am not versed in PHP at all:

    //request parameters
    $param_1 = $_POST['param1'];
    $param_2 = $_POST['param2'];
    
    echo 'postData: ' . var_dump($_POST);
    
    if ($_POST)){
        echo $param_1;
        echo $param_2;
    } else {
        echo 'problem';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染