iT邦幫忙

0

<已解決>我試著將JS陣列轉換成JSON格式,用.ajax POST 到另一個php。但是另一個php接收不到值,我不知道是哪裡寫錯了,這是我第一次使用.ajax

原本的問題不是這個,後來發現我想法走岔了,所以改了題目,因此回答看起來有點雞同鴨講,別在意......


如標題,alert告訴我JS這邊的轉換成功了。

alert陣列會跳S1,S2
alert轉換後的陣列會跳["S1","S2"]

但是另一個php接收不到值,我不知道是哪裡寫錯了

//將student array 宣告為JSON格式,並輸出給php
            var studentArrJson = JSON.stringify(allstudent);
            alert(studentArrJson);
            alert(allstudent);

            $.ajax({
                type: 'POST',
                url: 'TPchange.php',
                data: {studentArrJson: studentArrJson},
                dataType: 'json',
            });
//接收JSON格式的student陣列
$allstudent = json_decode($_POST['studentArrJson']);
var_dump($allstudent);

底下這段會出現Undefined index: studentArrJson並輸出NULL

看更多先前的討論...收起先前的討論...
haward79 iT邦研究生 3 級 ‧ 2021-06-15 10:51:06 檢舉
Code 請貼文字 ......
"我宣告了一個JS陣列" 這就是問題啊,樓主看需求要的是單一字串,不是陣列
那就 += 就好了,不用逐一指定
請不要貼圖片 ...
然後請檢查第二張圖的for迴圈 你的判斷式沒寫正確
AI_Hero iT邦新手 4 級 ‧ 2021-06-15 11:25:22 檢舉
不好意思剛剛發圖片,現在改成文字了
@窮嘶發發發 我設計是輸入完全部資料後,才按儲存一次送出全部資料,所以我想用陣列裝字串,到第二個php裡再for迴圈輸出字串,我不太懂你提到的+=是指什麼...
AI_Hero iT邦新手 4 級 ‧ 2021-06-15 11:25:38 檢舉
@screenleon具體來說是哪裡錯呢?第二段程式我還沒成功過,我還卡在現在問的陣列問題,沒注意第二段程式。
用陣列裝字串,你就不會問要把所有字串放在一起了,那就失去了陣列的意義
你把所有的字串塞到陣列內某個位置內,請問一下要拋到資料庫的時候你是不是還要再拆一次,這樣會比較好處理嘛,正常的邏輯就是一個字串一個位置,然後去輪詢陣列把值拋到資料庫,你如果非要把所有字串塞到同一個位置,當然就是用 += 啊,每次字串產生就加到同一個位置,只是你POST之後不可能用 FOR LOOP 拆字串而已
AI_Hero iT邦新手 4 級 ‧ 2021-06-15 14:23:53 檢舉
@窮嘶發發發 不好意思,我的形容不太好,讓你誤會了。我測試後發現是我對JS和php不夠熟悉。我現在把+=改成allstudent.push(student)了

原本我指的是把輸入的字串如"學生A",放進allstudent[0]裡,把第二個輸入的字串如"學生B"放進allstudent[1]中。

在第一個程式中allstudent[0]是"學生A",傳到php後卻變成allstudent[0]是"學",allstudent[1]是"生",似乎是JS傳值到php時出錯了,我不太懂為什麼會這樣,現在還在查詢
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
3
海綿寶寶
iT邦大神 1 級 ‧ 2021-06-15 10:54:30
最佳解答

https://ithelp.ithome.com.tw/upload/images/20210615/20001787Ikg0mZMkWj.png

bighead89916大大
你選錯最佳解答的人了
/images/emoticon/emoticon06.gif

AI_Hero iT邦新手 4 級 ‧ 2021-06-15 12:45:03 檢舉

哈哈,早上沒人回答時亂按的

1
screenleon
iT邦新手 1 級 ‧ 2021-06-15 11:27:28

要把值丟進陣列中,請參考以下

var test = [];
test.push('abc');
test.push(['ab','cd']);
test.push(...['123', '456'])
// output: [ 'abc', [ 'ab', 'cd' ], '123', '456' ]

第二段程式應該要小改

$i = 0;
for(;$i < count($allstudent); $i++){
	$sId = $allstudent[$i];
	$insert_exam = "INSERT INTO `exam` (`ID`, `sId`) VALUES ('$ID','$sId')";
}
看更多先前的回應...收起先前的回應...
AI_Hero iT邦新手 4 級 ‧ 2021-06-15 12:43:09 檢舉

非常感謝!!!
我剛剛試了一下,第二段報錯Warning: count(): Parameter must be an array or an object that implements Countable
用is_array($allstudent);檢查後系統說$allstudent不是陣列...

可是卻能輸出allstudent[0]/images/emoticon/emoticon19.gif

強制轉型成arr的話會把所有值塞進arr[0]裡

想問大大有沒有解決方法?

請善用框架提供的debug功能
或者把值先丟到html檢查,看是否如預期
要先了解你丟的內容跟接收到的有沒有相符
可以用print_r()來顯示

你也可以把資料用json輸出
最後再把資料從json_decode 回來

AI_Hero iT邦新手 4 級 ‧ 2021-06-15 16:56:57 檢舉

不好意思一直問這些基本問題...但是我試了很久都不知道正確的該怎麼寫

我試著將JS陣列轉換成JSON格式,用.ajax POST 到另一個php,alert告訴我JS這邊的轉換成功了。

alert陣列會跳S1,S2
alert轉換後的陣列會跳["S1","S2"]

但是另一個php接收不到值,我不知道是哪裡寫錯了,這是我第一次使用.ajax

//將student array 宣告為JSON格式,並輸出給php
            var studentArrJson = JSON.stringify(allstudent);
            alert(studentArrJson);
            alert(allstudent);

            $.ajax({
                type: 'POST',
                url: 'TPchange.php',
                data: {studentArrJson: studentArrJson},
                dataType: 'json',
            });
//接收JSON格式的student陣列
$allstudent = json_decode($_POST['studentArrJson']);
var_dump($allstudent);

底下這段會出現Undefined index: studentArrJson並輸出NULL

js是順序執行的 除非你有把它用函示包起來,或是增加event事件

function addStudent(student) {
                allstudent.push(student);
                var div = document.getElementById("student");
                var que = div.insertRow(-1);
                que.id = "que" + addstudent;
                var testName = que.insertCell(-1);
                testName.innerHTML = '<tr><td>' + student + '</td></tr>';
                addstudent = addstudent + 1;

                var studentArrJson = JSON.stringify(allstudent);
                $.ajax({
                    type: 'POST',
                    url: 'test.php',
                    data: { studentArrJson: studentArrJson },
                    dataType: 'json',
                });
            }

你應該是每當觸發按鈕時才會發送
那麼就應該把動作放到要觸發的事件當中 而不是放在外層
那自然你的動作只會執行一次,而且因為剛開始傳資料時為空值,自然甚麼都沒有

0

hi 不知道你的問題是不是這樣
php程式碼的部分

<?php
// 判斷有沒有post到php
if(isset($_POST["tophp"])){
    // 接收前端過來的陣列
    $list=$_POST["tophp"];
    $type = gettype($list);
    // 傳回給前端的判別型態
    echo json_encode($type); 
}

ajax程式碼的部分

$('#ex').click(function () {
    let arr=['123','111'];
    // 這樣php端接收為字串
    // arr_json=JSON.stringify(arr)
    // 這樣php端接收為array
    arr_json=arr;
    console.log(arr[0])
    $.ajax({
        type: "POST",
        url: "ex.php",
        dataType:"json", 
        data: {tophp:arr_json}, 
        success: function(data) {
            console.log('php回傳的'+data)
        },
        error: function(jqXHR) {
            console.log("沒回啦")
        }
    })
})

推斷你的ajax多寫了 var studentArrJson = JSON.stringify(allstudent);

你把這兩個交互觀察
arr_json=JSON.stringify(arr)
arr_json=arr;

至於這個
在第一個程式中allstudent[0]是"學生A",傳到php後卻變成allstudent[0]是"學"
我感覺allstudent[0]的輸出是:"
我感覺allstudent[1]的輸出是:學

AI_Hero iT邦新手 4 級 ‧ 2021-06-18 18:10:16 檢舉

感謝~好像就是這個!我型別方面不太熟,所以送錯類型了。

我要發表回答

立即登入回答