skip to Main Content

On the Django server side, I form a response:

def index(request):
    if request.method == 'POST':
        ...
        url = reverse(settlement_create, args=[settlement_id])
        return HttpResponse(marshal.dumps({'url': url}), content_type="application/json")

, where url=/settlement/154/create. jQuery cannot decode the byte string correctly and it turns out {� url� /settlement/154/create0.

    $.ajax({
      type : 'POST',
      url :  url,
      data : {'text': city_info},
      success : function(response){
          $("#city-href").attr('href', response['url']); 
      },
      error : function(response){
          console.log(response)
      }
  });

If you use a regular json library instead of marshal, then everything works fine. Do you have any ideas?

2

Answers


  1. // Assume that the byte string is stored in a variable called "byteString"
    
    // Convert the byte string to an ArrayBuffer
    var arrayBuffer = new ArrayBuffer(byteString.length);
    var bufferView = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteString.length; i++) {
      bufferView[i] = byteString.charCodeAt(i);
    }
    
    // Use the TextDecoder API to decode the ArrayBuffer into a string
    var decoder = new TextDecoder('utf-8');
    var decodedString = decoder.decode(arrayBuffer);
    
    // Use the decoded string as needed
    console.log(decodedString);
    

    In this code, the Uint8Array constructor is used to create a view of the ArrayBuffer that can be populated with the byte values from the byte string. The TextDecoder API is then used to decode the ArrayBuffer into a string using the UTF-8 encoding.

    Note that the TextDecoder API may not be supported in all browsers. If you need to support older browsers, you may need to use a polyfill or alternative library for decoding byte strings.

    Login or Signup to reply.
  2. I guess something is wrong with the encoder. You can just let Django do the work with a JsonResponse [Django-doc]:

    from django.http import JsonResponse
    
    
    def index(request):
        if request.method == 'POST':
            # …
            url = reverse(settlement_create, args=[settlement_id])
            return JsonResponse({'url': url})
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search